python时间模块datetime

datetime模块

datetime在python中比较常用,主要用来处理时间日期,使用前先倒入datetime模块。下面总结下本人想到的几个常用功能。

1、当前时间(日期、小时、字符串时....)

#当前时间
>>> datetime.datetime.now();
datetime.datetime(2018, 11, 1, 21, 49, 48, 330189) #当前日期
>>> datetime.datetime.now().date()
datetime.date(2018, 11, 1) #当前时间元祖
>>> datetime.datetime.now().timetuple()
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=1, tm_hour=22, tm_min=3, tm_sec=54, tm_wday=3, tm_yday=305, tm_is
dst=-1) #当前字符串时间
>>> datetime.datetime.now().strftime('%c')
'Thu Nov 1 23:21:52 2018' #当前时间戳
datetime.datetime.now().timestamp()

2、时间移动(几天、几小时后....)

使用datetime.timedelta这个方法来前后移动时间,可以用的参数有weeks,days,hours,minutes,seconds,microseconds。

>>> print datetime.datetime.now() + datetime.timedelta(days=1)
2015-07-18 16:49:48.574000
>>> print datetime.datetime.now() + datetime.timedelta(hours=1)
2015-07-17 17:49:57.122000
>>> print datetime.datetime.now() + datetime.timedelta(minutes=-30)
2015-07-17 16:20:08.619000

3、时间转化

datetime转str格式:

>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2015-07-17 16:58:46

str格式转datetime格式:

>>> datetime.datetime.strptime("2015-07-17 16:58:46","%Y-%m-%d %H:%M:%S")
datetime.datetime(2015, 7, 17, 16, 58, 46)
>>> print datetime.datetime.strptime("2015-07-17 16:58:46","%Y-%m-%d %H:%M:%S")
2015-07-17 16:58:46
>>> print type(datetime.datetime.strptime("2015-07-17 16:58:46","%Y-%m-%d %H:%M:%S"))
<type 'datetime.datetime'>

datetime转timestamp:

>>> import time
>>> now=datetime.datetime.now()
>>> time.mktime(now.timetuple())
1437123812.0

timestamp转datetime:

>>> datetime.datetime.fromtimestamp(1437123812.0)
datetime.datetime(2015, 7, 17, 17, 3, 32)
>>> print datetime.datetime.fromtimestamp(1437123812.0)
2015-07-17 17:03:32

参考网址:

https://docs.python.org/2/library/datetime.html

上一篇:python 时间处理(time和datetime介绍)


下一篇:python 时间模块time,datetime