Dror
Dror

Reputation: 13051

Python: parse string as time given two possible formats

I have a string s that can take two possible time formats:

timeShortFmt  = "%Y-%m-%d"
timeLongFmt   = "%Y-%m-%d %H:%M"

How can I safely parse s without knowing in advance which format it has? I am sure there's a smart pythonic way to do it (probably more than one). I can only come up with lengthy and cumbersome solutions.

Upvotes: 1

Views: 46

Answers (2)

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72795

Use the dateutil library parser. It handles fuzzy parsing of dates.

>>> from dateutil import parser
>>> parser.parse("2010-10-10")
datetime.datetime(2010, 10, 10, 0, 0)
>>> parser.parse("2010-10-10 13:40")
datetime.datetime(2010, 10, 10, 13, 40)

Upvotes: 1

jfs
jfs

Reputation: 414555

fmt = time_fmt_long if " " in input_string else time_fmt_short
dt = datetime.strptime(input_string, fmt)

Upvotes: 1

Related Questions