python 基础 7.1 datetime 获得时间

本文介绍了 Python 中 datetime 模块的基本使用方法,包括获取当前时间、格式化日期时间、计算日期间隔等实用技巧。
一 datatime 的使用
  object
        timedeta
        tzinfo
        time
        data
               datatime
     
      time: 在python文档里,time是归类在generk  operating  system services 中,换句话说,它提供的功能是更加接近于操作系统层面。
 
      python 开发过程中,我们经常用到获取当前时间,根据当前时间生成一个和当天时间相关的文件,这样我们在后期查找文件的时候就方便了很多,那python 又如何来获取当前时间的呢?
          from dateime import datetime
           now_time = datetime.now()
           a = now_time.strftime('%Y-%m-%d')
           print(now_time)
           print a
           print(type(now_time))
 
   strftime 时间参数有很多,介绍一些常用的时间参数:
   格式参数:
      %Y   带世纪部分的十进制年份
      %m  十进制表示的月份
       %d   十进制表示的每月的第几天
        %H   24小时制的小时
       %M     十时制表示的分钟数
         %s     十进制的秒数
         %c      标准时间
 
示例1:
#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/8 14:10
#@Auther :liuzhenchuan
#@File   :datatime.py
 
#time模块基本不用于取时间,取时间用datatime 模块
# time独有用法,alt + enter
import time
 
for i in xrange(1,10):
    print i
    time.sleep(0.3)
 
#datatime  获取当前时间
from datetime import datetime
now_time = datetime.now()
print now_time
 
#strftime 显示时间的格式
new1_time = now_time.strftime('%Y-%m-%d')
print new1_time
new2_time = now_time.strftime('%Y-%m-%d %H:%M:%S')
print new2_time
 
#打印标准时间
new3_time = now_time.strftime('%c')
print new3_time
 
>>>
1
2
3
4
5
6
7
8
9
2017-11-08 21:27:11.254000
2017-11-08
2017-11-08 21:27:11
11/08/17 21:27:11
 
 
 
示例2:
import datetime,timedelta
#timedelta 获取昨天的时间
now1_time = datetime.now()
yesterday = now1_time + timedelta(days=-1)
print yesterday
 
>>>
2017-11-07 22:01:51.766000
 
 
 
#打印明天的时间
tomorrow = now1_time + timedelta(days= +1)
tomorrow1 = tomorrow.strftime('%Y-%m-%d')
tomorrow1 = tomorrow.strftime('%c')
print tomorrow1
 
>>>  2017-11-09
            11/09/17 22:09:06
 
 
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

转载于:https://www.cnblogs.com/lzcys8868/p/7808105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值