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 = datetime.datetime.now()
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 = datetime.datetime.now()
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 = datetime.datetime.now()
time.sleep(30)
end = datetime.datetime.now()

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 = time.ctime() # '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

 

posted on 2016-12-22 14:04  刘[小]倩  阅读(72158)  评论(0编辑  收藏  举报

导航