简体   繁体   English

将奇怪的日期格式转换为标准日期格式

[英]Convert strange date format to standard date format

In Sweden we sometimes use a strange date format, for example New Year is the 31/12.在瑞典,我们有时会使用一种奇怪的日期格式,例如新年是 31/12。 If I have this format as a string ,which can be any date between 1/1 and 31/12, and if we assume that it is this year, how do I get into a standard date format using Python (format as 2012-01-01 and 2012-12-31) that can be sore in be stored as a date in a mySQL database.如果我将此格式作为字符串,它可以是 1/1 和 31/12 之间的任何日期,并且如果我们假设它是今年,我如何使用 Python 进入标准日期格式(格式为 2012-01 -01 和 2012-12-31) 可以作为日期存储在 mySQL 数据库中。

Simply split the two values, map them to integers and update a datetime.date() instance:简单地拆分两个值,将它们映射到整数并更新datetime.date()实例:

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

By using datetime.date.today() we get the current year.通过使用datetime.date.today()我们得到当前年份。

Demo:演示:

>>> 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)

Alternatively, you could use the datetime.strptime() method to parse these dates, but you'll have to manually correct the year afterwards (it'll use 1900 as the default if no year is being parsed):或者,您可以使用datetime.strptime()方法来解析这些日期,但您必须在之后手动更正年份(如果没有解析年份,它将使用 1900 作为默认值):

adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)

There is nothing strange about this format :)这种格式没有什么奇怪的:)

You can use the datetime module:您可以使用datetime模块:

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

>> datetime.date(2012, 12, 31)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM