請幫助我將日期時間對象(例如:2011-12-17 11:31:00-05:00
)(包括時區)更改爲Unix時間戳(如Python中的函數time.time())。在Python中將日期時間更改爲Unix時間戳
回答
不完整的答案(不處理時區),但希望有用:
time.mktime(datetime_object.timetuple())
**編輯基於以下注釋**
在我的程序中,用戶輸入的日期時間,選擇時區。 ...我創建了一個時區列表(使用pytz.all_timezones)並允許用戶從該列表中選擇一個時區。
Pytz模塊提供必要的轉換。例如。如果dt
是你datetime
對象,用戶選擇「美國/東方」
import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
的說法is_dst=True
是在夏令結束了1小時的間隔期間來解析不明確的時間(見這裏http://pytz.sourceforge.net/#problems-with-localtime)。
我真的需要處理時區。 – 2011-12-17 05:15:19
輸入日期時間對象是否包含正確的tzinfo?或者,如果不是,你怎麼知道你感興趣的時區? – 2011-12-17 05:40:19
另一種方法是:
import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
時間戳是Unix時間戳示出相同的日期與日期時間對象d。 [在Python轉換datetime.date到UTC時間戳](HTTP:
import time
import datetime
dtime = datetime.datetime.now()
ans_time = time.mktime(dtime.timetuple())
- 1. 將日期時間從mySql更改爲php中的時間戳
- 2. 將SAS日期時間轉換爲SAS中的UNIX時間戳
- 3. Unix時間戳VS日期時間
- 4. 將日期和時間轉換爲UNIX時代時間戳
- 5. 日期到Unix時間戳
- 6. 將日期時間格式轉換爲Unix時間戳Pandas
- 7. PHP將MySQL日期時間轉換爲Unix時間戳
- 8. 在Python中將未知時間戳轉換爲日期時間
- 9. PHP日期轉換爲unix時間戳
- 10. 在javascript中將unix日期時間戳轉換爲特定時區的時間
- 11. 熊貓:使用Unix時間戳時間戳作爲日期時間索引
- 12. Python:將Varbinary類型的時間戳轉換爲unix時間戳
- 13. 更改mySQL中的日期時間戳
- 14. 批量轉換並將日期時間列值更新爲UNIX時間戳?
- 15. 如何在MySql中將unix時間戳轉換爲UTC日期?
- 16. 從日期時間到時間戳python
- 17. 在Java中將整數日期/時間轉換爲unix時間戳?
- 18. 如何在UNIX中將UNIX時間戳轉換爲EST時間?
- 19. 如何將整數時間戳轉換爲Python日期時間
- 20. 將日期時間數組轉換爲時間戳Python
- 21. 加速將時間戳轉換爲日期時間Python
- 22. 將日期,日期時間轉換爲時間戳
- 23. 將日期和時間轉換爲日期+時間戳
- 24. 如何將時間戳更改爲mysql 5.5中的日期?
- 25. Bash腳本將日期和時間列轉換爲.csv中的unix時間戳
- 26. 將Unix時間戳轉換爲Perl中的可讀日期
- 27. 在Apex Salesforce中將Unix時間轉換爲日期時間
- 28. Unix時間戳和mysql日期:birthdate
- 29. 斯卡拉Unix時間戳到日期
- 30. jq日期和unix時間戳
可能http://stackoverflow.com/questions/2775864/python-datetime-to-unix-timestamp – 2011-12-18 04:08:32
相關的副本// stackoverflow.com/a/8778548/4279) – jfs 2013-05-26 01:40:24