Search code examples
pythondatetimeregex-group

How to make a datetime object of the date in a filename?


Im trying to extract the datetime inside a filename and make a datetime format of it like this: 2021-10-24 19:37:11

This is my code:

import re
import datetime

my_string = 'Afo_20211024-19u37m11s_ab.txt'
date_time= re.search("_(.\d+)_ab.txt", file_name).group(1)
"create a datetime here..."

This is my output:

'NoneType' object has no attribute 'group'


Solution

  • This is how I would do it. You can find the codes to use with datetime.strptime here: strftime() and strptime() Format Codes.

    The second argument to strptime is the pattern we are matching against. Each of the %X represent part of the datetime, but we also can have filler like '-' and 'u', 'm', 's' as part of the pattern.

    import datetime
    time_string = 'Afo_20211024-19u37m11s_ab.txt'.split('_')[1]
    date = datetime.strptime(time_string,'%Y%m%d-%Hu%Mm%Ss')
    

    If the files always start and end with the same stuff, and only the datetime part varies, then you could even get rid of line 2 and just have all of that start and end filler inside the datetime pattern.