user3388884
user3388884

Reputation: 5068

Pythonic way to get datetime from string without leading zero

Pythonic way to get datetime from a string without leading zeroes?

e.g. no leading zero for Hour (typical case)

'Date: Jul 10, 2014 4:41:28 PM'

Upvotes: 0

Views: 938

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

Without dateutil:

>>> import datetime
>>> d = datetime.datetime.strptime(s, 'Date: %b %d, %Y %I:%M:%S %p')
>>> d.hour
16
>>> d
datetime.datetime(2014, 7, 10, 16, 41, 28)

Upvotes: 2

alecxe
alecxe

Reputation: 473803

dateutil would handle it from out-of-the-box (fuzzy helps to ignore unrelated parts of the string):

>>> from dateutil import parser
>>> s = "Date: Jul 10, 2014 4:41:28 PM"
>>> parser.parse(s, fuzzy=True)
datetime.datetime(2014, 7, 10, 16, 41, 28)

Upvotes: 4

Related Questions