Python: casting an integer into a datatime stamp
Python: casting an integer into a datatime stamp
I am finding it very difficult to convert the following list l:
l
l = [0, 1]
into the time stamps corresponding to the indices of the following dataframe df:
df
dt val
2017-11-13 00:00:00 8
2017-11-13 01:00:00 17
Ideally the result has to be:
l = [2017-11-13 00:00:00, 2017-11-13 01:00:00]
so I can identify these two timesteps in the plot of a longer time series that overlaps df.
df
What's the best way of doing this? My attempt fails miserably and I can't make sense of the correct timestamp format:
index1 = pd.to_datetime(str(df.index[l[0]]), format='%Y-%m-%d %H:%M:%S')
index2 = pd.to_datetime(str(df.index[l[1]]), format='%Y-%m-%d %H:%M:%S')
This throws the error:
ValueError: time data '2017-11-13 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' (match)
print(str(df.index[l[0]]))
2 Answers
2
I believe need list comprehension with fstrings:
f
d = pd.to_datetime([f'2017-11-13 x:00:00' for x in l], format='%Y-%m-%d %H')
print(d)
DatetimeIndex(['2017-11-13 00:00:00', '2017-11-13 01:00:00'],
dtype='datetime64[ns]', freq=None)
Performance (depends of real data):
np.random.seed(2018)
l = np.random.randint(12, size=1000).tolist()
In [48]: %%timeit
...: d = pd.to_datetime([f'2017-11-13 x:00:00' for x in l], format='%Y-%m-%d %H')
647 µs ± 2.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [49]: %%timeit
...: d = pd.to_datetime('2017-11-13' +
pd.Index(l).astype(str).str.zfill(2), format='%Y-%m-%d%H')
...:
4.43 ms ± 22 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
There are several ways, but here's one without an explicit loop or specifying a format:
L = [0, 1]
datetime = pd.to_datetime('2017-11-13') + pd.to_timedelta(L, unit='h')
Result:
DatetimeIndex(['2017-11-13 00:00:00', '2017-11-13 01:00:00'],
type='datetime64[ns]', freq=None)
Your solution won't work because str does not work in a vectorised way.
str
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What does
print(str(df.index[l[0]]))output?– CristiFati
Sep 12 '18 at 10:45