Python的time和datetime模块提供了时间日期工具, python中的时间有4种表示方式:
datetime obj
time obj/tuple
posix timestamp
timestring
datetime
获得当前时间:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 21, 16, 21, 51, 631199)
创建datetime对象:
>>> d = datetime.datetime(year=2016, month=1, day=1, hour=12, minute=0, second=0)
>>> d
datetime.datetime(2016, 1, 1, 12, 0)
>>> d.year
2016
datetime是不可变对象, 若要修改时间需要建立新的datetime对象.
但是datetime可以相减,比较或加减timedelta:
>>> datetime.datetime.now() - d
datetime.timedelta(233, 16611, 887646)
>>> datetime.datetime.now() < d
False
>>> datetime.datetime.now() + datetime.timedelta(1)
datetime.datetime(2016, 8, 22, 16, 38, 30, 306021)
转换为time tuple:
>>> d.timetuple()
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=1, tm_isdst=-1)
通过time tuple转换为时间戳:
>>> time.mktime(datetime.datetime.now().timetuple())
1471777789.0
格式化为时间字符串:
>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
'2016-08-21 16:46:20 634139'
time
获得当前时间:
>>> import time
>>> time.localtime()
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=21, tm_hour=16, tm_min=48, tm_sec=24, tm_wday=6, tm_yday=234, tm_isdst=0)
转换为datetime:
>>> datetime.datetime(*time.localtime()[0:6])
datetime.datetime(2016, 8, 21, 16, 56, 16)
格式化为时间字符串:
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
'2016-08-21 16:55:01'
转换为时间戳:
>>> time.mktime(time.localtime())
1471770256.0
时间戳
UNIX时间戳定义为1970-1-1 00:00:00开始的秒数, 获得当前时间戳:
>>> import time
>>> time.time()
1471777412.3293073
转换为datetime:
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2016, 8, 21, 19, 8, 22, 719951)
转换为timetuple:
>>> time.localtime(time.time())
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=21, tm_hour=19, tm_min=13, tm_sec=41, tm_wday=6, tm_yday=234, tm_isdst=0)