Python-将月份名称转换为整数 [英] Python - Convert Month Name to Integer
本文介绍了Python-将月份名称转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Datetime将 Jan转换为整数?尝试strptime时,出现错误时间数据'Jan'与格式'%m'
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'
推荐答案
您有一个缩写的月份名称,因此请使用%b
:
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
是数字月份。
但是,如果您只想将一个缩写的月份映射到一个数字,则只需使用字典即可。您可以通过 calendar.month_abbr
构建一个:
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}
演示:
>>> 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
这篇关于Python-将月份名称转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文