我有一個字符串日期爲2015-03-25T00:00:00Z
。我如何將它轉換爲unix時代1426636800000.0
如何將字符串日期轉換爲python中的紀元時間戳
Python中是否有任何庫可以這樣做。
我有一個字符串日期爲2015-03-25T00:00:00Z
。我如何將它轉換爲unix時代1426636800000.0
如何將字符串日期轉換爲python中的紀元時間戳
Python中是否有任何庫可以這樣做。
使用時間,例如。
所以首先你需要將字符串轉換爲時間對象(或者你可以使用datetime或halex提到的方式),然後獲得自epoch以來的秒數。
>>> import time
>>> time.mktime(time.strptime('2015-03-25T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))
1427241600.0
time.strptime(string[, format])
import time
print time.strptime("2015-03-25T00:00:00Z","%Y-%m-%dT%H:%M:%SZ")
如果你有Python的3.3或更新版本,你可以使用datetime模塊:
>>> import datetime
>>> datetime.datetime.strptime("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ").timestamp()
1427238000.0
AttributeError:'datetime.datetime'對象沒有屬性'timestamp'是拋出的錯誤 – user2890683 2015-03-25 11:14:17
@ user2890683哦。我忘了提及['timestamp'](https://docs.python.org/3.4/library/datetime.html#datetime.datetime.timestamp)是在Python 3.3中引入的。好像你正在使用Python2。抱歉給你帶來不便。 – halex 2015-03-25 11:15:53
您可以使用easy_date以方便:
import date_converter
timestamp = date_converter.string_to_timestamp("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")
這看起來像一個ISO日期已經回答[這裏](http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python) – 2015-03-25 11:01:21
另外,你可以看到一些在http://stackoverflow.com /問題/ 11743 019 /轉換的Python-日期時間到劃時代與-的strftime。 – user1929959 2015-03-25 11:02:13