简体   繁体   English

无论输入格式如何,将日期转换为python中的特定格式

[英]Convert date into a specific format in python irrespective of the input format is

I have a problem statement to convert the dates into a specific format.我有一个问题陈述将日期转换为特定格式。 However, the input can be of any format.但是,输入可以是任何格式。 For example,例如,

Input输入 Desired_output期望输出
2020/11/20 2020/11/20 2020-11-20 2020-11-20
20201120 20201120 2020-11-20 2020-11-20
20202011 20202011 2020-11-20 2020-11-20
11/20/2020 11/20/2020 2020-11-20 2020-11-20
202020Nov 20202011月 2020-11-20 2020-11-20

I'm able to solve where is a delimiter present in between year, month and date using the Dateutil package.我能够使用 Dateutil 包解决年、月和日期之间存在分隔符的位置。 But it is not able to solve where is no clear delimiter.但它无法解决没有明确分隔符的地方。

Is there any way to solve this problem?有没有办法解决这个问题?

I don't think there is an easy way to universally parse dates that don't follow the standard formats .我认为没有一种简单的方法可以普遍解析不遵循标准格式的日期。 You'll have to specify the format in which the date is written for it to be parsed, which you can easily do using strptime (see here for a reference on datetime formatting).您必须指定写入日期的格式以供解析,您可以使用strptime轻松完成(有关日期时间格式的参考,请参见此处)。

A package like dateutil can be helpful as well.dateutil这样的包也很有帮助。 You should take a look, however, at the accepted date formats .但是,您应该查看接受的日期格式 In general, dateutil is more convenient, but strptime gives you more control and ability to parse more date formats.一般来说, dateutil更方便,但strptime为您提供了更多的控制权和解析更多日期格式的能力。

Four out of the five examples you mentioned can be parsed using dateutil as follows:您提到的五个示例中有四个可以使用dateutil进行解析,如下所示:

from dateutil import parser
parser.parse("2020/11/20")   # Output: datetime.datetime(2020, 11, 20, 0, 0)
parser.parse("11/20/2020")   # Output: datetime.datetime(2020, 11, 20, 0, 0)

For the two other examples, the dayfirst and yearfirst arguments are needed to let dateutil parse them correctly:对于另外两个示例,需要dayfirstyearfirst参数才能让dateutil正确解析它们:

parser.parse("20201120", yearfirst=True)
parser.parse("20202011", yearfirst=True, dayfirst=True)
# Output for both: datetime.datetime(2020, 11, 20, 0, 0)

Finally, I'm not aware of a way to parse the date "202020Nov" using dateutil ;最后,我不知道使用dateutil解析日期"202020Nov"方法; however, it can be parsed using strptime as follows:但是,它可以使用strptime解析如下:

from datetime import datetime
datetime.strptime("202020Nov", "%Y%d%b")
# Output: datetime.datetime(2020, 11, 20, 0, 0)

All the best.一切顺利。

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

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