我收到此錯誤:
ValueError: time data '2022-01-20T15:30:57.2648531Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'
這是我的代碼:
import datetime
date_string = '2022-01-20T15:30:57.2648531Z'
date_format = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
unix_time = datetime.datetime.timestamp(date_format)
print(unix_time)
我已經測驗了洗掉時間資料中的最終數字并且它有效。看來您在毫秒位置只能有 6 個數字。有沒有辦法繞過/解決這個問題?
uj5u.com熱心網友回復:
不幸的是,datetime.datetime該類僅支持從0到的微秒999999。觀察:
>>> import datetime
>>> datetime.datetime(2022, 1, 20, 15, 30, 57, 2648531)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
datetime.datetime(2022, 1, 20, 15, 30, 57, 2648531)
ValueError: microsecond must be in 0..999999
>>>
但是,即使您竭盡全力將微秒與字串分開以添加到unix_time,您仍然會遇到丟失 的問題1:
import datetime
date_string = '2022-01-20T15:30:57.2648531Z'
index = date_string.rindex(".")
ms = float(date_string[index: -1])
date_format = datetime.datetime.strptime(date_string[:index], "%Y-%m-%dT%H:%M:%S")
unix_time = datetime.datetime.timestamp(date_format) ms
print(unix_time)
輸出:
1642721457.264853
那是因為 python 根本不支持浮點數的這種精度:
>>> 1642721457.2648531
1642721457.264853
uj5u.com熱心網友回復:
看來您在毫秒位置只能有 6 個數字
它實際上是微秒,說明%f符匹配一個 6 位數的微秒值。如果您有 7 位數字,則精度超過 1 微秒。
datetime物件不支持比微秒更高的精度,所以你可以扔掉最后一個數字。您可以通過多種方式執行此操作。由于根據您的格式說明符,您的字串應始終具有相同的長度,因此您可以在轉換之前簡單地對其進行修剪。
import datetime
date_string = '2022-01-20T15:30:57.2648531Z'
date_string = date_string[:26] # trim anything past the 6th decimal digit
d = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f")
print(d.timestamp())
由于您的日期是 ISO 格式,您也可以使用datetime.datetime.fromisoformat(),這應該會讓您的生活更輕松:
import datetime
date_string = '2022-01-20T15:30:57.2648531Z'
date_string = date_string[:26] # trim anything past the 6th decimal digit
d = datetime.datetime.fromisoformat(date_string)
print(d.timestamp())
uj5u.com熱心網友回復:
使用datetime只會讓你到目前為止(6位數)。改用pd.to_datetime:
unix_time = pd.to_datetime(date_string)
print(unix_time.value)
輸出:
1642692657264853100
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418651.html
標籤:
