β

convert python datetime unix timestamp

Rex.Zhang.name 163 阅读

代码


import datetime, calendar, time

#----------------------------------------------------------------------
def timestamp2datetime(timestamp):
""""""
return datetime.datetime.fromtimestamp(timestamp)

#----------------------------------------------------------------------
def date2timestamp(date):
"""local time"""
return calendar.timegm(date.timetuple())

#----------------------------------------------------------------------
def date2timestamp_utc(date):
"""utc time"""
return int(time.mktime(date.timetuple()))

#----------------------------------------------------------------------
def datetime2timestamp(year, month, day):
""""""
return calendar.timegm(datetime.datetime(year, month, day).timetuple())

#----------------------------------------------------------------------
def time2timestamp(python_time):
""""""
return int(python_time)

year = 2014
month = 10
day = 23
timestamp = datetime2timestamp(year, month, day)
print timestamp

today = datetime.datetime.today()
timestamp = date2timestamp(today)
print timestamp
timestamp = date2timestamp_utc(today)
print timestamp

date = timestamp2datetime(timestamp)
print date

timestamp = time2timestamp(time.time())
print timestamp

输出

00
local timestamp: 1422462994
utc timestamp: 1422434194
-01-28 16:36:34
434194

另外, unix timestamp -> python 还有 datetime.utcfromtimestamp() date.fromtimestamp() 函数可用

参考

Update

作者:Rex.Zhang.name
从记录到不仅是记录
原文地址:convert python datetime unix timestamp, 感谢原作者分享。