Python 将Django中的DateTimeField转换为Unix时间

Python 将Django中的DateTimeField转换为Unix时间,python,django,Python,Django,在我的Django项目中,我在模型中使用了DateTimeField。这实际上包含pythondatetime.datetime实例 从新纪元开始,最快的时间转换方法是什么(以秒为单位) 我认为这对您很有用。在Python 3.3+中,您可以使用: 对于早期版本的Python,您可以执行以下操作: # Format it into seconds >>> datetime.datetime(2012,04,01,0,0).strftime('%s') '1333234800'

在我的Django项目中,我在模型中使用了
DateTimeField
。这实际上包含python
datetime.datetime
实例

从新纪元开始,最快的时间转换方法是什么(以秒为单位)


我认为这对您很有用。

在Python 3.3+中,您可以使用:

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

使用
%s
(因为它的实现依赖于操作系统)会遇到任何问题吗?@HassanBaigI不知道这一点。你能分享一些文件吗?值得一读的是:)王的评论,我不同意这是重复的。如果您有一个datetime字段Django,并且想要unix时间戳,那么可以执行以下操作:
Project.objects.get(id=1)
。现在可以通过
Project.objects.get(id=1)[0]['created_at']].timestamp()访问时间戳。
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
# 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