Home > Enterprise >  How to convert time stamp in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsm
How to convert time stamp in Python from dd/mm/yy hh:mm:ss:msmsms to yyyy-mm-dd hh:mm:ss:msmsmsmsmsm

Time:11-16

I have created an automated data client that pulls data from a txt file and inputs it into a csv file. Each data entry contains a timestamp, but it is not in the format I need it in, I need it to match the datetime.now() format:

ORIGINAL FORMAT [03/11/22 01:06:09:190]

DESIRED FORMAT 2022-11-03 01:06:09.190000

I am currently using the following code to pull the timestamp from each line of data I need: 82: reTimestamp = r'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}:\d{3}'

105:     for line in f:
106:         line.strip()
108:     timestamp = re.findall(reTimestamp, line.strip())

110: print(timestamp)

Output: ['03/11/22 01:05:06:172']

Every function is working well up until now because im having trouble converting this timestamp to the desired format. I would also like to get rid of the square brackets '[]'

CodePudding user response:

Looks like timestamp is a list, to access the string try timestamp[0]

And you can convert the string to your desired datetime format using the below code

from datetime import datetime
timestamp = ['03/11/22 01:05:06:172']
datetime_object = datetime.strptime(timestamp[0], '%d/%m/%y %H:%M:%S:%f')
date_time = datetime_object.strftime("%Y-%m-%d %H:%M:%S.%f")
date_time
#Output: 2022-11-03 01:05:06.172000

CodePudding user response:

The square brackets mean it is a list. You can get rid of them by selecting the first item in the list:

print(timestamp[0])

As for the date conversions, use the built-in datetime package

  • Related