0

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'
user3388884
  • 4,208
  • 6
  • 22
  • 34
  • 1
    possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – Cory Kramer Jul 22 '14 at 18:56
  • same here http://stackoverflow.com/questions/2265357/parse-date-and-format-it-using-python – FrEaKmAn Jul 22 '14 at 18:58

2 Answers2

4

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)
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
2

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)
Burhan Khalid
  • 161,711
  • 18
  • 231
  • 272