Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Convert Month Name to Integer

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'

like image 890
huhh hhbhb Avatar asked Aug 03 '15 21:08

huhh hhbhb


People also ask

How do I get the month number in Python?

In order to get the month number from a datetime object in Python, all you need to do is use the . month method.

How do I change the month format in Python?

Use strftime() function of a datetime class For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


2 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
like image 88
Martijn Pieters Avatar answered Oct 16 '22 06:10

Martijn Pieters


Off the cuff- Did you try %b?

like image 33
AndrewSmiley Avatar answered Oct 16 '22 07:10

AndrewSmiley