18

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'

3
  • 1
    Note that strptime is affected by your locale setting Commented Aug 3, 2015 at 21:16
  • %m is month as number. I think you want %b. see: strftime.org Commented Aug 3, 2015 at 21:39
  • possible duplicate of python convert string to datetime Commented Aug 3, 2015 at 22:41

4 Answers 4

27

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
Sign up to request clarification or add additional context in comments.

8 Comments

I get 1900-01-01 00:00:00 out of that
@huhhhhbhb: yes, what did you expect? If you don't include a year or day, the rest of the values fall back to defaults.
True, I really just wanted to get a single digit corresponding to the month number
@huhhhhbhb To get a month number from datetime instance use datetime.strptime('Feb', '%b').month which gives 2.
@Anthony: then you have more than just a full month name and using datetime.strptime() makes sense.
|
1

This is straightforward enough that you could consider just using a dictionary, then you have fewer dependencies anyway.

months = dict(Jan=1, Feb=2, Mar=3, ...)
print(months['Jan'])
>>> 1

Comments

1

Off the cuff- Did you try %b?

3 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
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.
Oooh I see. Didn't realize that was a standardized message. Thanks!
1
from calendar import month_abbr
month = "Jun"
for k, v in enumerate(month_abbr):
    if v == month:
        month = k
        break
print(month)

6

You will get the number of month 6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.