15

How can I parse a string like "01-Jan-1995" to a Python datetime object?

davidism
  • 110,080
  • 24
  • 357
  • 317
Charlie Epps
  • 3,515
  • 9
  • 31
  • 38

3 Answers3

24

On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:

import datetime
datetime.datetime.strptime("01-Jan-1995", "%d-%b-%Y")

Note that parsing month names is locale-dependent. This table shows the directives for parsing various formats of dates and times.

EricP
  • 3,303
  • 3
  • 31
  • 45
Tuure Laurinolli
  • 3,768
  • 1
  • 19
  • 20
10

dateutil can parse this sort of format without you even having to define custom date formats. Just install it with:

pip install python-dateutil

Then use it:

import dateutil.parser
dateutil.parser.parse('01-Jan-1995').date()
Soviut
  • 83,904
  • 44
  • 175
  • 239
  • 2
    +1 for python-dateutil. It can even parse datestrings without you having to tell it the format. – unutbu Nov 11 '09 at 18:44
1

If you need to parse natural language date and time strings, consider parsedatetime (and this answer).

Community
  • 1
  • 1
Adam Matan
  • 117,979
  • 135
  • 375
  • 532