python-杂碎知识2-time和datetime.
相关用法见如下代码:
1.time
import time # 获取当前时间戳 print(time.time()) # 获取时间元祖 print(time.localtime()) # 时间戳转换为时间元组 time_stuple = time.localtime(time.time()) print(time_stuple) # 时间元祖转换为时间戳 time_chuo = time.mktime(time_stuple) print(time_chuo) # 获取当前时间格式字符串 now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) print(now_time) #时间转换为元组 time_stuple1 = time.strptime("2021-11-25 20:29:35",'%Y-%m-%d %H:%M:%S') print(time_stuple1)
运行结果:
1637847545.277951
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=25, tm_hour=21, tm_min=39, tm_sec=5, tm_wday=3, tm_yday=329, tm_isdst=0)
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=25, tm_hour=21, tm_min=39, tm_sec=5, tm_wday=3, tm_yday=329, tm_isdst=0)
1637847545.0
2021-11-25 21:39:05
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=25, tm_hour=20, tm_min=29, tm_sec=35, tm_wday=3, tm_yday=329, tm_isdst=-1)
2.datetime
import datetime # 获取当前时间 print(datetime.datetime.now()) print(datetime.datetime.today()) #转换为时间戳 time_chuo1 = datetime.datetime.now().timestamp() print(time_chuo1) #时间戳转换为时间 time2 = datetime.datetime.fromtimestamp(time_chuo1) print(time2) #获取当前时间转换为字符串 time3 = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S") print(time3) #字符串转换datetime pdatetime = datetime.datetime.strptime('2021-6-1 18:19:59.10', '%Y-%m-%d %H:%M:%S.%f') print(pdatetime)
运行结果:
2021-11-25 21:39:05.285930
2021-11-25 21:39:05.285930
1637847545.28593
2021-11-25 21:39:05.285930
2021-11-25 21-39-05
2021-06-01 18:19:59.100000
每篇一句:
心姐说,今天给我讲一个好笑的:鲸鱼的鼻子在头上。
本文来自博客园,作者:Titen,转载请注明原文链接:https://www.cnblogs.com/chengxiazuohua/p/15605152.html