Convert a string, representing a list of timestamps, to list of timestamps

Question:

I have a string input represnting a list of timestamps. An exampe of such string is shown below:

‘[Timestamp(‘2022-08-13 17:25:00’), Timestamp(‘2022-08-13 18:02:00’), Timestamp(‘2022-08-13 18:46:00′)]’

I need to convert it to a list of timestamps in python. How can I do that in a right way?

Asked By: HoseinPanahi

||

Answers:

Since you tagged , you can approach this with pd.Series constructor and pd.to_datetime.

Try this :

import pandas as pd

s = "[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), Timestamp('2022-08-13 18:46:00')]"


L = (
        pd.Series(s.strip("[]").split(","))
            .str.extract("'(.*)'", expand=False)
            .apply(pd.to_datetime)
            .to_list()
    )

# Output :

print(L)

[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), Timestamp('2022-08-13 18:46:00')]
Answered By: abokey

A solution without pandas, using regex to identify the relevant strings in your big string, then datetime.strptime to converts them to actual datetimes:

tstring = "[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), Timestamp('2022-08-13 18:46:00')]"

import re
from datetime import datetime as dt
dtstrings = re.findall(r"('([^,]*)')",tstring)
datetimes = [dt.strptime(x,'%Y-%m-%d %H:%M:%S') for x in dtstrings]

datetimes
# Out[84]: [datetime.datetime(2022, 8, 13, 17, 25),
# datetime.datetime(2022, 8, 13, 18, 2),
# datetime.datetime(2022, 8, 13, 18, 46)]
Answered By: Swifty

A way without pandas resulting in a list of timestamps:

timestamps="[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), 
Timestamp('2022-08-13 18:46:00')]"
# remove square brackets from string and split on "," to create a list from string
timestamps = timestamps[1 :-1 : ].split(", ")
# remove timestamp substrings
dates_ = [elem.replace("Timestamp('","").replace("')","") for elem in 
timestamps]
import datetime
#as datetime
ts_as_datetime = [datetime.datetime.strptime(elem, '%Y-%m-%d %H:%M:%S') for elem in dates_]

#and finally as Timestamp as required:
ts_as_timestamp = [datetime.datetime.timestamp(element) for element in ts_as_datetime]

Regards,
Jehona.

Answered By: Jehona Kryeziu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.