joe smith
joe smith

Reputation: 29

How to pull a datetime object out of multiple file names?

I have a mutiple files that I want to create a datetime object from, an example is as such:

corr_20060122_082009_vt_unfolded 

and I wanted to created a datetime object. 2006 is year, 01 month, 22 day, 08 hour, 20 mins, 09 seconds, time is in the 24 hour format (military time) in the file name. For all the filenames how can I pull a datetime object? Is there some way of extracting the datetime from multiple files? Thank you.

Upvotes: 1

Views: 52

Answers (1)

Asish M.
Asish M.

Reputation: 2647

>>> import re
>>> from datetime import datetime

>>> s = re.findall(r'\d+_\d+', 'corr_20060122_082009_vt_unfolded')[0]
>>> datetime.strptime(s, '%Y%m%d_%H%M%S')
datetime.datetime(2006, 1, 22, 8, 20, 9)

Upvotes: 1

Related Questions