Python之时间字符串、时间戳、时间差、任意时间字符串转换
时间对象
1. 时间字符串 --> 时间戳
1) time 模块
timestring = '2016-12-21 10:22:56'
print time.mktime(time.strptime(timestring, '%Y-%m-%d %H:%M:%S')) # 1482286976.0
time.mktime() 与 time.localtime() 互为还原函数。
time.mktime(timetuple) :将时间元组转换成时间戳
time.localtime([timestamp]):将时间戳转会为时间元组
2) datetime 模块
在这⾥没有到,似乎只有 time 模块能获取时间戳
2. 时间戳 --> 时间字符串
1) time 模块
timestamp = time.time()
timestruct = time.localtime(timestamp)
print time.strftime('%Y-%m-%d %H:%M:%S', timestruct) # 2016-12-22 10:49:57
2) datetime 模块
import datetime
timestamp = 1482374997.55
datetime_struct = datetime.datetime.fromtimestamp(timestamp)
print datetime_struct.strftime('%Y-%m-%d %H:%M:%S') # 2016-12-22 10:49:57
datetime_struct = datetime.datetime.utcfromtimestamp(timestamp)
print datetime_struct.strftime('%Y-%m-%d %H:%M:%S') # 2016-12-22 02:49:57
fromtimestamp(timestamp[, tz]):将时间戳转为当地的时间元组
utcfromtimestamp(timestamp):将时间戳转为UTC的时间元组。以北京为例:utc时间⽐北京当地时间少8个⼩时。
3. 时间差计算
1)⼏天/周前
import datetime
now = w()
three_days_ago = now + datetime.timedelta(days=-3)
three_weeks_ago = now + datetime.timedelta(weeks=-3)
print now # datetime.datetime(2016, 12, 22, 11, 24, 49, 987171)
print three_days_ago # datetime.datetime(2016, 12, 19, 11, 24, 49, 987171)
print three_weeks_ago # datetime.datetime(2016, 12, 1, 11, 24, 49, 987171)
2)⼏天/周后
import datetime
now = w()
three_days_later = now + datetime.timedelta(days=3)
three_weeks_later = now + datetime.timedelta(weeks=3)
print now # datetime.datetime(2016, 12, 22, 11, 24, 49, 987171)
print three_days_later # datetime.datetime(2016, 12, 25, 11, 24, 49, 987171)
print three_weeks_later # datetime.datetime(2017, 1, 12, 11, 24, 49, 987171)
注意:没有months和years
3)时间差
import time
import datetime
start = w()
time.sleep(30)
交易时间字符串是什么end = w()
print (end-start).days # 0 天数
print (end-start).total_seconds() # 30.029522 精确秒数
print (end-start).seconds # 30 秒数
print (end-start).microseconds # 29522 毫秒数
注意:没有分钟
4. 任意时间字符串转换时间对象
import time
from dateutil import parser
time_string = ime() # 'Thu Dec 22 10:35:25 2016',这⾥可以是任意的时间格式datetime_struct = parser.parse(time_string)
print type(datetime_struct) # <type 'datetime.datetime'>
print datetime_struct.strftime('%Y-%m-%d %H:%M:%S') # 2016-12-22 13:58:59
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论