将Django中的DateTimeField转换为Unix tim

2024-10-01 17:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的一个Django项目中,我在模型中使用DateTimeField。这实际上有pythondatetime.datetime实例。

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


Tags: 项目django实例模型datetime时间单位纪元
2条回答
datetime.datetime(date).strftime('%s')

我想这对你有用。

在Python 3.3+中,您可以使用^{}

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

对于早期版本的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

相关问题 更多 >

    热门问题