2016-11-17 28 views
4

轉換DateTimeField字段在我的Django項目,我在模型中使用DateTimeField。這實質上有python datetime.datetime實例。在Django到Unix時間

什麼是最快的方式將它轉換爲時間紀元以來(以秒爲單位)?

回答

8

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

>>> 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 
+1

一個可以運行到使用'%s'任何問題(因爲它的實現取決於操作系統)? –

+0

@HassanBaigI不知道這件事。你能分享一些文件嗎?這將是值得一讀:) –

+1

王的評論http://stackoverflow.com/a/11111177/4936905 –

3
datetime.datetime(date).strftime('%s') 

我認爲它適合你。