题
如何在python中将datetime或date对象转换为POSIX时间戳?有一些方法可以从时间戳中创建一个日期时间对象,但我似乎没有找到任何明显的方法以相反的方式进行操作。
解决方案
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
其他提示
对于UTC计算, calendar.timegm
是 time.gmtime
的反转。
import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
请注意,Python now(3.5.2)包含已构建-in方法,用于 datetime
对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.timestamp() # Local time
1509315202.161655
>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC
1509329602.161655
在python中,time.time()可以返回秒作为包含带微秒的小数部分的浮点数。为了将日期时间转换回此表示形式,您必须添加微秒组件,因为直接时间元组不包含它。
import time, datetime
posix_now = time.time()
d = datetime.datetime.fromtimestamp(posix_now)
no_microseconds_time = time.mktime(d.timetuple())
has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001
print posix_now
print no_microseconds_time
print has_microseconds_time
不隶属于 StackOverflow