-->

Is there a wildcard format directive for strptime?

2019-05-08 13:40发布

问题:

I'm using strptime like this:

import time
time.strptime("+10:00","+%H:%M")

but "+10:00" could also be "-10:00" (timezone offset from UTC) which would break the above command. I could use

time.strptime("+10:00"[1:],"%H:%M")

but ideally I'd find it more readable to use a wildcard in front of the format code.

Does such a wildcard operator exist for Python's strptime / strftime?

回答1:

There is no wildcard operator. The list of format directives supported by strptime is in the docs.

What you're looking for is the %z format directive, which supports a representation of the timezone of the form +HHMM or -HHMM. While it has been supported by datetime.strftime for some time, it is only supported in strptime starting in Python 3.2.

On Python 2, the best way to handle this is probably to use datetime.datetime.strptime, manually handle the negative offset, and get a datetime.timedelta:

import datetime

tz = "+10:00"

def tz_to_timedelta(tz):
    min = datetime.datetime.strptime('', '')
    try:
        return -(datetime.datetime.strptime(tz,"-%H:%M") - min)
    except ValueError:
        return datetime.datetime.strptime(tz,"+%H:%M") - min

print tz_to_timedelta(tz)

In Python 3.2, remove the : and use %z:

import time
tz = "+10:00"
tz_toconvert = tz[:3] + tz[4:]
tz_struct_time = time.strptime(tz_toconvert, "%z")


回答2:

We developed datetime-glob to parse date/times from a list of files generated by a consistent date/time formatting. From the module's documentation:

>>> import datetime_glob
>>> matcher = datetime_glob.Matcher(
                         pattern='/some/path/*%Y-%m-%dT%H-%M-%SZ.jpg')

>>> matcher.match(path='/some/path/some-text2016-07-03T21-22-23Z.jpg')
datetime_glob.Match(year = 2016, month = 7, day = 3, 
                    hour = 21, minute = 22, second = 23, microsecond = None)

>>> match.as_datetime()
datetime.datetime(2016, 7, 3, 21, 22, 23)