Python “违约”;“未来”;使用dateutil进行日期转换时的年份
以下日期模式Python “违约”;“未来”;使用dateutil进行日期转换时的年份,python,python-datetime,python-dateutil,Python,Python Datetime,Python Dateutil,以下日期模式 1st January 30th April 通过dateutil.parser.parse(),可以轻松地解析为datetime.date的实例: 如何从解析返回未来日期? 也就是说,解析“1月1日”将返回datetime.datetime(2013,1,1,0,0),2013年1月1日,而不是2012年1月1日。有什么优雅的解决方案吗?首先,这里有一个解决方案,它可以在没有指定年份的情况下确定日期,并确保日期不在过去。如果年份作为字符串的一部分给出,那么它将保持不变 impo
1st January
30th April
通过dateutil.parser.parse()
,可以轻松地解析为datetime.date
的实例:
如何从解析返回未来日期?
也就是说,解析“1月1日”
将返回datetime.datetime(2013,1,1,0,0)
,2013年1月1日,而不是2012年1月1日。有什么优雅的解决方案吗?首先,这里有一个解决方案,它可以在没有指定年份的情况下确定日期,并确保日期不在过去。如果年份作为字符串的一部分给出,那么它将保持不变
import datetime
import dateutil
def parse(date_string):
result = dateutil.parser.parse(date_string, default=datetime.datetime(1581, 1, 1))
if result.year == 1581:
now = datetime.datetime.now()
result = result.replace(year=now.year)
if result < now:
result = result.replace(year=now.year + 1)
return result
parse('8th April')
导入日期时间
导入dateutil
def解析(日期字符串):
result=dateutil.parser.parse(日期\字符串,默认值=datetime.datetime(1581,1))
如果result.year==1581:
now=datetime.datetime.now()
结果=结果.替换(年=现在.年)
如果结果<现在:
结果=结果。替换(年份=现在。年份+1)
返回结果
解析(“4月8日”)
首先,这里有一个解决方案,它不需要指定年份的日期,并确保它们不是过去的日期。如果年份作为字符串的一部分给出,那么它将保持不变
import datetime
import dateutil
def parse(date_string):
result = dateutil.parser.parse(date_string, default=datetime.datetime(1581, 1, 1))
if result.year == 1581:
now = datetime.datetime.now()
result = result.replace(year=now.year)
if result < now:
result = result.replace(year=now.year + 1)
return result
parse('8th April')
导入日期时间
导入dateutil
def解析(日期字符串):
result=dateutil.parser.parse(日期\字符串,默认值=datetime.datetime(1581,1))
如果result.year==1581:
now=datetime.datetime.now()
结果=结果.替换(年=现在.年)
如果结果<现在:
结果=结果。替换(年份=现在。年份+1)
返回结果
解析(“4月8日”)
谢谢!但是现在它不起作用了dateutil.parse
将不起作用,因此我将通过从dateutil.parser导入parse
,并将您的方法parse
重命名为parse\u future
。让它运行的简单步骤,但是一旦运行它就会返回datetime.datetime(1581,4,8,0,0)
@JosvicZammit,我想我已经修复了它。我正在调试。result.replace(year=now.year+1)
是不起作用的部分。问题是,即使是“4月28日”也要到2013年,而我希望它保持不变。如果您同意,请批准。干杯@JosvicZammit,replace
不会更改日期时间,它会返回一个新的日期时间-这是我最初犯的一个大错误。我不知道为什么我更新的代码在“4月28日”不起作用,你完全复制了吗?谢谢!但是现在它不起作用了dateutil.parse
将不起作用,因此我将通过从dateutil.parser导入parse
,并将您的方法parse
重命名为parse\u future
。让它运行的简单步骤,但是一旦运行它就会返回datetime.datetime(1581,4,8,0,0)
@JosvicZammit,我想我已经修复了它。我正在调试。result.replace(year=now.year+1)
是不起作用的部分。问题是,即使是“4月28日”也要到2013年,而我希望它保持不变。如果您同意,请批准。干杯@JosvicZammit,replace
不会更改日期时间,它会返回一个新的日期时间-这是我最初犯的一个大错误。我不知道为什么我更新的代码在“4月28日”不起作用,你完全复制了吗?