[英]Turning Numpy array values to datetime values with List comprehensions Python
我正在嘗試在它通過ts
數組的地方編寫一個列表理解,然后將其轉換為可讀的時間戳。 但是, dates
列表理解有誤,我如何才能修復它並獲得下面的預期 Output?
from datetime import datetime
import numpy as np
ts = np.array([1628997394, 1628997444, 1628997602, 1629006977, 1629007021])
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
dates=[x for x in ts if ts > 0 datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')]
錯誤:
dates=[x for x in ts if ts > 0 datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')]
^
SyntaxError: invalid syntax
預計 Output:
[2021-08-15 03:16:34 , 2021-08-15 03:17:24, 2021-08-15 03:20:02 , 2021-08-15 05:56:17 , 2021-08-15 05:57:01]
if
您應該檢查x
不檢查ts
和ts
的結尾for
並且if
檢查條件時是否需要寫入 datetime.utcfromtimestamp( x
datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')
在您要創建的列表的第一個。
嘗試這個:
from datetime import datetime
import numpy as np
ts = np.array([1628997394, 1628997444, 1628997602, 1629006977, 1629007021])
dates=[datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S') for x in ts if x>0]
Output:
['2021-08-15 03:16:34',
'2021-08-15 03:17:24',
'2021-08-15 03:20:02',
'2021-08-15 05:56:17',
'2021-08-15 05:57:01']
要檢查運行時兩種解決方案,您可以使用%timeit
並查看何時可以使用list
完成工作,不要使用numpy
或pandas
,因為使用附加庫並不好。 (對於這個短數組,使用list
比使用pandas
快 10 倍)
運行:
ts = np.array([1628997394, 1628997444, 1628997602, 1629006977, 1629007021])
%timeit dates=[datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S') for x in ts if x>0]
# 27.1 µs ± 899 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit pd.to_datetime(ts, unit='s', errors='coerce').dropna().astype(str).to_numpy()
# 708 µs ± 128 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
使用pandas
可以更有效地完成它:
>>> import pandas as pd
>>> ts = np.array([1628997394, 1628997444, 1628997602, 1629006977, 1629007021])
>>> pd.to_datetime(ts, unit='s', errors='coerce').dropna().astype(str).to_numpy()
array(['2021-08-15 03:16:34', '2021-08-15 03:17:24',
'2021-08-15 03:20:02', '2021-08-15 05:56:17',
'2021-08-15 05:57:01'], dtype=object)
>>>
import numpy as np
import pandas as pd
ts = np.array([1628997394, 1628997444, 1628997602, 1629006977, 1629007021])
ts1 = pd.to_datetime(ts, unit='s', errors= 'coerce')
ts1
解決方案:
DatetimeIndex(['2021-08-15 03:16:34', '2021-08-15 03:17:24',
'2021-08-15 03:20:02', '2021-08-15 05:56:17',
'2021-08-15 05:57:01'],
dtype='datetime64[ns]', freq=None)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.