繁体   English   中英

使用列表理解将 Numpy 数组值转换为日期时间值 Python

[英]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不检查tsts的结尾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完成工作,不要使用numpypandas ,因为使用附加库并不好。 (对于这个短数组,使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM