使用strptime()转换日期 [英] Date conversion with strptime()
本文介绍了使用strptime()转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中将以下日期格式转换为 datetime.date
对象的最佳方式是什么?
4月1日
pre>
4月8日
4月15日
1月5日
解决方案
dateutil.parser
将解析几乎所有已知的日期格式:
from dateutil.parser import parse
parse('8th August')
将来总是得到一个日期:
from dateutil.parser import parse
from datetime import datetime
d = parse('8th August')
if(d - datetime.now())。days< ; = 0:
d = datetime.date(d.year + 1,d.month,d.day)
What is the best way to convert the following date pattern to a
datetime.date
object in Python?1st April 8th April 15th April 1st May
解决方案
dateutil.parser
will parse almost every known date format:from dateutil.parser import parse parse('8th April')
To always get a date in the future:
from dateutil.parser import parse from datetime import datetime d = parse('8th April') if (d - datetime.now()).days <= 0: d = datetime.date(d.year+1, d.month, d.day)
这篇关于使用strptime()转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文