练习题
1. 当前月1号对应的0点的时间戳
now_time = time.strftime('%Y-%m-01 00:00:00')
jiegou = time.strptime(now_time, '%Y-%m-%d %H:%M:%S')
shijiancuo = time.mktime(jiegou)
print('%s对应的时间戳为%s'%(now_time,shijiancuo))
2. n1的时间 n2的时间 n2 - n1的时间经历里多少年 月 日 时 分 秒
- 思想:需要首先将两个字符串时间转换为时间戳格式,然后相减,再转换为结构化时间,然后减去时间戳最开始时间(伦敦时间:1970/01/01 00:00:00)
import time
n1 = '2019-07-18 20:07:56'
n2 = '2019-07-19 22:03:12'
struct_time1, struct_time2 = time.strptime(n1, '%Y-%m-%d %H:%M:%S'), time.strptime(n2, '%Y-%m-%d %H:%M:%S')
struct_time1, struct_time2 = time.mktime(struct_time1), time.mktime(struct_time2)
diff_time = struct_time2 - struct_time1
struct_time = time.gmtime(diff_time)
print('过去了{0}年{1}月{2}日{3}小时{4}分钟{5}秒'.format(
struct_time.tm_year-1970,
struct_time.tm_mon-1,
struct_time.tm_mday-1,
struct_time.tm_hour,
struct_time.tm_min,
struct_time.tm_sec
))