Python date wild card

872
3
Jump to solution
08-12-2019 07:22 AM
AndrewL
Occasional Contributor II

Hi I have the following code that works correctly. However, every once in a while there is a file name that has an "06" instead of an "05" and it breaks the script. Is there a way I can use a wild card for that digit?

        fileName = os.path.split(fullFileName)[-1]
        fileNameShort = fileName[:-13]
        fileDateTime = dt.strptime(fileName, "%m%d%Y_%H05shapefile.zip")‍‍‍‍‍‍
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Does this work for you?

>>> import datetime
>>> 
>>> file = "08112019_0005shapefile.zip"
>>> fileDateTime = datetime.datetime.strptime(file[:13], "%m%d%Y_%H%M")
>>> fileDateTime = fileDateTime.replace(minute=0)
>>> fileDateTime
datetime.datetime(2019, 8, 11, 0, 0)
>>> 

View solution in original post

3 Replies
JoshuaBixby
MVP Esteemed Contributor

How you are applying the date format for datetime.strptime is unusual, even if it is working.  Typically, the date/time formatting only includes date/time components and not additional text.

It seems you are working with a group of files that have consistent naming, can you provide an example of a file name and what you are trying to get because there might be a better overall approach.

0 Kudos
AndrewL
Occasional Contributor II

Sure. We use the Weather Climate Toolkit (a program from NOAA) to automatically download the zip files every hour. They are named after the date/time they are downloaded. However, recently it sometimes takes more than one minute to download a file which causes it to have an "06" instead of "05." Thanks.

08112019_0005shapefile.zip

08112019_0105shapefile.zip

08112019_0205shapefile.zip

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Does this work for you?

>>> import datetime
>>> 
>>> file = "08112019_0005shapefile.zip"
>>> fileDateTime = datetime.datetime.strptime(file[:13], "%m%d%Y_%H%M")
>>> fileDateTime = fileDateTime.replace(minute=0)
>>> fileDateTime
datetime.datetime(2019, 8, 11, 0, 0)
>>>