本文介绍python当中表示时间的数据之间如何进行转换,涉及到的数据类型和模块包括datetime, 时间戳,字符串,time,在实践中,我们总能遇到这方面的需求。
获得当前时间的时间戳有两种方法
import time
from datetime import datetime
# 获得当前时间戳
current_time = int(time.time())
print(current_time)
now = datetime.now()
current_time = int(now.timestamp())
print(current_time)
程序输出结果
1577761708
1577761708
from datetime import datetime
current_time = 1577761708
date_time = datetime.fromtimestamp(current_time)
print(date_time)
import time
current_time = 1577761708
print(time.ctime(current_time)) # 转换成 Tue Dec 31 11:08:28 2019
print(time.localtime(current_time)) # 转成时间元组,本地时间
print(time.gmtime(current_time)) # 转成时间元组,国际伦敦时间
localtime_tuple = time.localtime(current_time) # 将时间元组转成时间戳
current_time = time.mktime(localtime_tuple)
print(current_time)
from datetime import datetime
now = datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S") # 将datetime转成字符串
print(now_str)
date_time = datetime.strptime(now_str, "%Y-%m-%d %H:%M:%S") # 将字符串转成datetime类型
print(date_time, type(date_time))
import time
time_str = '2019-12-31 11:22:23'
res = time.strptime(time_str, '%Y-%m-%d %H:%M:%S') # 将字符串转成时间元组
print(res, type(res))
now = time.localtime()
now_str = time.strftime('%Y-%m-%d %H:%M:%S', now) # 将时间元组转成字符串
print(now_str)
from datetime import datetime
now = datetime.now()
print(now.ctime()) # 返回ctime() 格式时间字符串
print(now.timetuple()) # 返回时间元组
QQ交流群: 211426309