将Django中的DateTimeField转换为Unix时间

Has*_*aig 6 python django

在我的Django项目中,我正在使用DateTimeField模型.这基本上有python datetime.datetime实例.

从纪元(以秒为单位)转换到时间的最快方法是什么?

Moi*_*dri 13

在Python 3.3+中,您可以使用datetime.timestamp():

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Run Code Online (Sandbox Code Playgroud)

对于早期版本的Python,您可以:

# Format it into seconds
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

# OR, subtract the time with 1 Jan, 1970 i.e start of epoch time
# get the difference of seconds using `total_seconds()`
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
Run Code Online (Sandbox Code Playgroud)