2011-08-30 117 views

回答

70

應該這樣做

import time 

date_time = '29.08.2011 11:05:02' 
pattern = '%d.%m.%Y %H:%M:%S' 
epoch = int(time.mktime(time.strptime(date_time, pattern))) 
print epoch 
+7

這僅適用於服務器的時區。 – eumiro

+1

因爲正在使用mktime,這是否意味着您應該將返回的時期調整爲UTC? – ChuckCottrill

+0

感謝您的回答! Upvoted。 –

10

假設你使用的是24小時時間格式:

import time; 
t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S")); 
4
import time 
def expires(): 
    '''return a UNIX style timestamp representing 5 minutes from now''' 
    return int(time.time()+300) 
9
Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata' 

So, you need to do below 

>>> import time, os 
>>> d='2014-12-11 00:00:00' 
>>> p='%Y-%m-%d %H:%M:%S' 
>>> epoch = int(time.mktime(time.strptime(d,p))) 
>>> epoch 
1418236200 
>>> os.environ['TZ']='UTC' 
>>> epoch = int(time.mktime(time.strptime(d,p))) 
>>> epoch 
1418256000 
+0

錯字,你的代碼片段應該是:os.environ ['TZ'] ='UTC'。請注意,TZ的關鍵字是「 – sateesh

2
如果你想UTC嘗試一些 gm功能

import time 
import calendar 

date_time = '29.08.2011 11:05:02' 
pattern = '%d.%m.%Y %H:%M:%S' 
utc_epoch = calendar.timegm(time.strptime(date_time, pattern)) 
print utc_epoch 
相關問題