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)






What does print(str(df.index[l[0]])) output?

– CristiFati
Sep 12 '18 at 10:45


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ