声明:参考B站视频,自学成长记录
https://www.bilibili.com/video/BV1u44114753?p=88
1、查看时间戳200000000对应的年月日
'''
时间戳 -> 结构化 -> 格式化
'''
struct_t = time.localtime(2000000000)
time_f = time.strftime('%Y-%m-%d',struct_t)
print(time_f) # 2033-05-18
2、将2020-11-11 转成时间戳
'''
格式化 -> 结构化 -> 时间戳
'''
struct_t = time.strptime('2020-11-11', '%Y-%m-%d')
t = time.mktime(struct_t)
print(t) # 1605024000.0
3、获取当前时间的当前月1号的时间戳
def get_time():
# 获取当前时间
struct_t = time.localtime()
# 获取当前月的1号时间
struct_t_1 = time.strptime(\
'{}-{}-1'.format(struct_t.tm_year,struct_t.tm_mon), '%Y-%m-%d')
return time.mktime(struct_t_1)
print(get_time()) # 1625068800.0
4、计算时间差
def get_sub_time(time1, time2):
'''
获取两个时间之差
:param time1: 时间1
:param time2: 时间2
:return:
'''
# 格式化 -> 结构化
struct_t1 = time.strptime(time1, '%Y-%m-%d %H:%M:%S')
struct_t2 = time.strptime(time2, '%Y-%m-%d %H:%M:%S')
# 结构化 -> 时间戳
ts1 = time.mktime(struct_t1)
ts2 = time.mktime(struct_t2)
# 两个时间的时间戳差
sub_time = ts2 - ts1
# 转成伦敦时间戳
gm_time = time.gmtime(sub_time)
# 与 1970-1-1 00:00:00 相减
sub_time_f = ('时间差为: {}年{}月{}日{}时{}分{}秒'.format( \
gm_time.tm_year - 1970, \
gm_time.tm_mon - 1, \
gm_time.tm_mday - 1, \
gm_time.tm_hour, \
gm_time.tm_min, \
gm_time.tm_sec))
return sub_time_f
time1 = '2021-08-08 08:08:08'
time2 = '2021-08-08 18:18:18'
sub_time = get_sub_time(time1, time2)
print(sub_time) # 时间差为: 0年0月0日10时10分10秒
5、根据年月日判断是那一年的第几天
import time
'''
'''
def get_yday(tm):
# 将输入的年月日转成时间戳格式
tm = time.mktime(time.strptime(tm,'%Y-%m-%d'))
# 根据时间戳获取 结构化时间
data_num = time.localtime(tm)
# 返回 tm_yday
return data_num.tm_yday
print(get_yday('1993-11-11')) # 315