Al-Andalus
Al-Andalus

Reputation: 135

How to create a datetime object from a string?

I tried to be smart and create a one liner which can extract the datetime of my_string and make a datetime of it. However, it did not work quiet well.

my_string = 'London_XX65TR_20211116_112413.txt'

This is my code:

datetime=  datetime.datetime.strptime(my_string .split('_')[2],'%Y%m%d_%H%M%S')

This is my output:

ValueError: time data '20211116' does not match format '%Y%m%d_%H%M%S'

Upvotes: 2

Views: 4614

Answers (5)

from datetime import datetime

date_time_str = '18/09/19 01:55:19'

date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')


print ("The type of the date is now",  type(date_time_obj))
print ("The date is", date_time_obj)

Upvotes: 0

hpchavaz
hpchavaz

Reputation: 1388

Your code does not work because my_string .split('_') gives ['London', 'XX65TR', '20211116', '112413.txt'] so in strptime('20211116', '%Y%m%d_%H%M%S') return an error.

You should either :

  1. limit the format to `'%Y%m%d', loosing the HMS
  2. find another way to get the whole substring matching the format

The first part of the alternative is trivial so lets go for the second one using regex.

import regex as re
datetime = datetime.datetime.strptime(re.search(r'\d{8}_\d{6}', my_string)[0],'%Y%m%d_%H%M%S')

Upvotes: 0

rathourdevesh
rathourdevesh

Reputation: 1

The Method you are following is correct. It's just you are not considering the HH:MIN:Sec part and need to append that before formatting,

my_string = 'London_XX65TR_20211116_112413.txt'
my_date = (my_string .split('_')[2]+my_string .split('_')[3]).replace(".txt","")
datetime=  datetime.datetime.strptime(my_date,'%Y%m%d%H%M%S')
print(datetime) # 2021-11-16 11:24:13

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You could use the maxsplit argument in str.split:

>>> from datetime import datetime
>>> region, code, date_time = my_string[:-4].split('_', maxsplit=2)
>>> datetime.strptime(date_time, "%Y%m%d_%H%M%S")
datetime.datetime(2021, 11, 16, 11, 24, 13)

Which means only split at, at most maxsplit occurrences of the _ characters from the left, leave the rest as is.


For this particular case, instead of my_string[:-4], you could use my_string.rstrip('.txt'), it is not advised in general, because it may strip some useful information as well. Whereas, from Python 3.9+ you could use str.removesuffix:

>>> my_string = 'London_XX65TR_20211116_112413.txt'
>>> region, code, date_time = my_string.removesuffix('.txt').split('_', maxsplit=2)
>>> datetime.strptime(date_time, "%Y%m%d_%H%M%S")
datetime.datetime(2021, 11, 16, 11, 24, 13)

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520998

You could use re.findall here:

from datetime import datetime

my_string = 'London_XX65TR_20211116_112413.txt'
ts = re.findall(r'_(\d{8}_\d{6})\.', my_string)[0]
dt = datetime.strptime(ts, '%Y%m%d_%H%M%S')
print(dt)  # 2021-11-16 11:24:13

This approach uses a regex to extract the timestamp from the input string. The rest of your logic was already correct.

Upvotes: 2

Related Questions