Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a wildcard format directive for strptime?

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?

like image 824
blippy Avatar asked Mar 31 '12 21:03

blippy


People also ask

What is the difference between Strptime and Strftime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

How do I use Strftime and Strptime in Python?

Python time strptime() MethodThe format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.

What does the P stand for in Strptime?

p for produce, str p time (strptime)-> string produces time.

What does Strptime return?

The strftime() method returns a string representing date and time using date, time or datetime object.


1 Answers

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")
like image 128
agf Avatar answered Oct 21 '22 15:10

agf