datetime在python中比较常用,主要用来处理时间日期,使用前先倒入datetime模块,下面总结一下本人用到的常用功能。
1.当前时间
In [30]: datetime.datetime.now()
Out[30]: datetime.datetime(2018, 9, 11, 10, 40, 30, 190295)
2.当前日期
In [32]: datetime.datetime.now().date()
Out[32]: datetime.date(2018, 9, 11)
3.当前时间tuple
In [35]: datetime.datetime.now().timetuple()
Out[35]: time.struct_time(tm_year=2018, tm_mon=9, tm_mday=11, tm_hour=10, tm_min=44, tm_sec=35, tm_wday=1, tm_yday=254, tm_isdst=-1)
4.时间移动(几天、几小时前后...)
使用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
上个月最后一天
>>> print datetime.date(day=1,month=datetime.date.today().month,year=datetime.date.today().year) - datetime.timedelta(days=1)
2015-06-30
自然月的时间移动
https://dateutil.readthedocs.io/en/stable/relativedelta.html
In [13]: import datetime In [14]: from dateutil.relativedelta import relativedelta In [15]: a = datetime.datetime(2018,8,31) In [16]: b = a - relativedelta(months=+6) In [17]: a Out[17]: datetime.datetime(2018, 8, 31, 0, 0) In [18]: b Out[18]: datetime.datetime(2018, 2, 28, 0, 0)
5.获取两个时间的时间差
>>> (datetime.datetime.now() - datetime.datetime.utcnow()).total_seconds()
28800.0
6.时间转化
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