1

在瑞典,我们有时会使用一种奇怪的日期格式,例如新年是 31/12。如果我将此格式作为字符串,可以是 1/1 和 31/12 之间的任何日期,如果我们假设是今年,我如何使用 Python 进入标准日期格式(格式为 2012-01 -01 和 2012-12-31)可以作为日期存储在 mySQL 数据库中。

4

2 回答 2

2

只需拆分这两个值,将它们映射到整数并更新一个datetime.date()实例:

import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)

通过使用datetime.date.today()我们得到当前年份。

演示:

>>> import datetime
>>> somevalue = '31/12'
>>> day, month = map(int, somevalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 12, 31)
>>> someothervalue = '1/1'
>>> day, month = map(int, someothervalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 1, 1)

或者,您可以使用该datetime.strptime()方法来解析这些日期,但之后您必须手动更正年份(如果没有解析年份,它将使用 1900 作为默认值):

adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)
于 2012-11-08T15:54:22.553 回答
0

这种格式没有什么奇怪的:)

您可以使用该datetime模块:

import datetime
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012)
print d

>> datetime.date(2012, 12, 31)
于 2012-11-08T16:12:51.337 回答