前言:公司前端的时间参数分为两类 一种是时间戳传参,另一种是 2023-01-11T16:00:00Z (UTC)时间传参,有些脚本需要用到datatime.datatime因此要整理一下相关方法
获取时间戳
my_timestamp=time.time()
print(my_timestamp) # 1673492215.2460585
时间戳转time.struct_time
传参时间戳(int or float) 返回为time.struct_time
my_localtime = time.localtime(time.time()) # 默认为当前时间 可以添加时间参数[时间戳 或浮点时间戳] 可以通过索引 a[0] a.tm_mon 两种方式取值
# my_localtime= time.localtime(1672502400)
print(my_localtime) # time.struct_time(tm_year=2023, tm_mon=1, tm_mday=12, tm_hour=10, tm_min=40, tm_sec=22, tm_wday=3, tm_yday=12, tm_isdst=0)
时间戳转格式化字符串
传参 时间格式,time.struct_time 返回 格式化字符串
my_strftime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 获取当前 格式化字符串 时间
print(my_strftime) # 2023-01-12 10:40:22 格式化字符串
时间戳转 utc/gmt的time.struct_time
传参 时间戳(int or float) 返回gmt时间的time.struct_time
my_gmtime = time.gmtime() # 默认参数为当前时间戳 可以写入时间戳
print(my_gmtime) # time.struct_time(tm_year=2023, tm_mon=1, tm_mday=12, tm_hour=2, tm_min=46, tm_sec=29, tm_wday=3, tm_yday=12, tm_isdst=0)
字符串转time.struct_time
my_strptime=time.strptime("2023-01-01 23:59:59","%Y-%m-%d %H:%M:%S")
print("1",my_strptime)
time.struct_time转时间戳
my_mktime=time.mktime(time.localtime(time.time()))
print(my_mktime)
应用1 字符串转时间戳
- 思路 格式化字符串–time.struct_time–时间戳
import time
my_to_timestamp=time.mktime(time.strptime("2023-01-01 23:59:59","%Y-%m-%d %H:%M:%S"))
print("1",my_to_timestamp) # 1672588799.0
应用2 datetime.datetime到2023-01-11T16:00:00.000Z格式的utc/gmt时间
- 思路 datetime.datetime–格式化字符串–time.struct_time–时间戳–utc/gmt的time.struct_time–格式化字符串
import datetime
import time
# datetime.datetime--格式化字符串
my_datetime = datetime.datetime(2023, 1, 1, 0, 0, 0)
# print(type(my_datetime)) # <class 'datetime.datetime'>
# print(my_datetime) # 2023-01-01 00:00:00
my_datetime_str = str(my_datetime)
# 格式化字符串--time.struct_time
my_datetime_str_strptime=time.strptime(my_datetime_str,"%Y-%m-%d %H:%M:%S")
# time.struct_time--时间戳
my_datetime_str_strptime_mktime=time.mktime(my_datetime_str_strptime)
# time.struct_time--utc/gmt的time.struct_time
my_datetime_str_strptime_mktime_gmtime=time.gmtime(my_datetime_str_strptime_mktime)
# utc/gmt的time.struct_time--格式化字符串2023-01-11T16:00:00.000Z
d=time.strftime("%Y-%m-%dT%H:%M:%SZ", my_datetime_str_strptime_mktime_gmtime)
print(d) # 2022-12-31T16:00:00Z
文章出处登录后可见!
已经登录?立即刷新