Home > OS >  Convert a string, representing a list of timestamps, to list of timestamps
Convert a string, representing a list of timestamps, to list of timestamps

Time:12-11

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?

CodePudding user response:

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')]

CodePudding user response:

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)]

CodePudding user response:

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.

  • Related