简体   繁体   English

从日期 4.5.6 中提取日、月和年

[英]Extraction of day, month and year from the date 4.5.6

Which function can I use to extract day, month and year from dates written in this manner 4.5.6 where 4 is the day, 5 is the month and 6 is the year (presumably 2006).我可以使用哪个函数从以这种方式编写的日期中提取日、月和年 4.5.6 其中 4 是日期,5 是月份,6 是年份(大概是 2006 年)。 I have already tried using dateparser.parse but it is not working.我已经尝试过使用 dateparser.parse 但它不起作用。

day, month, year = map(int, '4.5.6'.split('.'))

And then add 2000 as necessary to the year.然后根据需要在年份中添加 2000。

You can then construct a datetime object with然后你可以构造一个日期时间对象

from datetime import datetime
dt = datetime(year, month, day)

While it would be logical to use datetime.strptime , the one-digit year messes things up, and the above will just work fine.虽然使用datetime.strptime是合乎逻辑的,但一位数的年份会把事情搞砸,而上述内容就可以正常工作。

Here is how you can use the datetime.datetime.strptime() method:以下是如何使用datetime.datetime.strptime()方法:

import datetime

s = "4.5.6"
i = s.rindex('.') + 1
s = s[:i] + s[i:].rjust(2, '0') # Add padding to year
dt = datetime.datetime.strptime(s, "%d.%m.%y")
print(dt)

Output:输出:

2006-05-04 00:00:00

With the resulting datetime.datetime object, you can access plenty of information about the date, for example you can get the year by printing dt.year (outputs 2006 ) .使用生成的datetime.datetime对象,您可以访问大量有关日期的信息,例如您可以通过打印dt.year (outputs 2006 )来获取年份。

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

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