How can I convert 'Jan' to an integer using Datetime? When I try strptime, I get an error time data 'Jan' does not match format '%m'
4 Answers
You have an abbreviated month name, so use %b:
>>> from datetime import datetime
>>> datetime.strptime('Jan', '%b')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.strptime('Aug', '%b')
datetime.datetime(1900, 8, 1, 0, 0)
>>> datetime.strptime('Jan 15 2015', '%b %d %Y')
datetime.datetime(2015, 1, 15, 0, 0)
%m is for a numeric month.
However, if all you wanted to do was map an abbreviated month to a number, just use a dictionary. You can build one from calendar.month_abbr:
import calendar
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
Demo:
>>> import calendar
>>> abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
>>> abbr_to_num['Jan']
1
>>> abbr_to_num['Aug']
8
8 Comments
huhh hhbhb
I get
1900-01-01 00:00:00 out of thatMartijn Pieters
@huhhhhbhb: yes, what did you expect? If you don't include a year or day, the rest of the values fall back to defaults.
huhh hhbhb
True, I really just wanted to get a single digit corresponding to the month number
AXO
@huhhhhbhb To get a month number from datetime instance use
datetime.strptime('Feb', '%b').month which gives 2.Martijn Pieters
@Anthony: then you have more than just a full month name and using
datetime.strptime() makes sense. |
Off the cuff-
Did you try %b?
3 Comments
J Richard Snape
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
J Richard Snape
Sure, it came to me in a review queue and that is a standard message for when further info is requested in an answer. If you edit it to say - e.g. - "you need to use %b", then it likely wouldn't be flagged for review.
AndrewSmiley
Oooh I see. Didn't realize that was a standardized message. Thanks!
strptimeis affected by your locale setting%mis month as number. I think you want%b. see: strftime.org