[英]Convert a Date in String Format to a datetime.date
I have some strings which come to me in formats like 我有一些像这样的格式的字符串
29-Jul-2014
or 03-Aug-2015
29-Jul-2014
或03-Aug-2015
What is the easiest way to convert this to a datetime.date
object? 将其转换为
datetime.date
对象的最简单方法是什么?
I can only think to make a dictionary like d = {'Jul': 7, 'Aug': 8, ...}
and then do 我只能想到制作像
d = {'Jul': 7, 'Aug': 8, ...}
这样的字典,然后执行
dt = datetime.date(year, d[month], day)
Is there any other easier way and avoid the creation of this dictionary? 还有其他更简单的方法来避免创建此字典吗?
Thanks 谢谢
Use datetime.datetime.strptime
to convert the string to datetime.datetime
object. 使用
datetime.datetime.strptime
将字符串转换为datetime.datetime
对象。
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y')
datetime.datetime(2014, 7, 29, 0, 0)
Then, use datetime.datetime.date
method to convert it to datetime.date
object: 然后,使用
datetime.datetime.date
方法将其转换为datetime.date
对象:
>>> datetime.datetime.strptime('29-Jul-2014', '%d-%b-%Y').date()
datetime.date(2014, 7, 29)
The easy way is use dateutil.parse
module, it lets to parse the common date formats, even if you don't know what it is using currently 简单的方法是使用
dateutil.parse
模块,即使您不知道当前使用的格式,它也可以解析常用的日期格式
Ex: 例如:
>>> import dateutil.parser
>>>
>>> utc_time = '2014-07-29T00:00:00'
>>> verbose_time = '29-Jul-2014'
>>> some_locale = '29/7/14'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 7, 29, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 7, 29, 0, 0)
Once you have a datetime object, you only should invoke the datetime.date() method 拥有datetime对象后,仅应调用datetime.date()方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.