關注時分秒
import time
# time stamp
print('time stamp: {}'.format(time.time()))
print('type of time: {}'.format(type(time.time())))
# time stamp: 1515080614.0703459
# type of time: <class 'float'>
# struct_time
print('local time: {}'.format(time.localtime()))
print('type of local time: {}'.format(type(time.localtime())))
print('gmt time: {}'.format(time.gmtime()))
# local time: time.struct_time(tm_year=2018, tm_mon=1, tm_mday=4, tm_hour=23, tm_min=43, tm_sec=34, tm_wday=3, tm_yday=4, tm_isdst=0)
# type of local time: <class 'time.struct_time'>
# gmt time: time.struct_time(tm_year=2018, tm_mon=1, tm_mday=4, tm_hour=15, tm_min=43, tm_sec=34, tm_wday=3, tm_yday=4, tm_isdst=0)
# type of gmt time: <class 'time.struct_time'>
# string
print('type of gmt time: {}'.format(type(time.gmtime())))
print(time.ctime(time.time()))
# custom string
print(time.strftime("%Y-%m-%d, %H:%M:%S, %w", time.gmtime()))
# Thu Jan 4 23:43:34 2018
# 2018-01-04, 15:43:34, 4
關注年月日時分秒
datetime可比大小,相減後得到timedelta物件
import datetime
datetime_now = datetime.datetime.now()
print('datetime_now: {}'.format(datetime_now))
print('type of datetime_now: {}'.format(type(datetime_now)))
# datetime_now: 2018-01-05 00:08:08.024173
# type of datetime_now: <class 'datetime.datetime'>
datetime_now_utc = datetime.datetime.utcnow()
print('datetime_now_utc: {}'.format(datetime_now_utc))
print('type of datetime_now_utc: {}'.format(type(datetime_now_utc)))
# datetime_now_utc: 2018-01-04 16:08:08.024224
# type of datetime_now_utc: <class 'datetime.datetime'>
today = datetime.date.today()
print('today: {}'.format(today))
print('type of today: {}'.format(type(today)))
# today: 2018-01-05
# type of today: <class 'datetime.date'>
if datetime_now > datetime_now_20180101:
print('latest:{}'.format(datetime_now))
else:
print('latest:{}'.format(datetime_now_20180101))
# latest:2018-01-05 00:19:23.513402
time_difference = datetime_now - datetime_now_20180101
print('time_difference: {}'.format(time_difference))
print('total seconds:{}'.format(time_difference.total_seconds()))
print('type of time_difference: {}'.format(type(time_difference)))
# time_difference: 4 days, 0:19:23.513402
# total seconds:346763.513402
# type of time_difference: <class 'datetime.timedelta'>