Python datetime.strptime - 将String格式的月份转换为Digit

时间:2022-05-11 15:45:39

I have a string that contains the date in this format: full_date = "May.02.1982"

我有一个字符串,其中包含此格式的日期:full_date =“May.02.1982”

I want to use datetime.strptime() to display the date in all digits like: "1982-05-02"

我想使用datetime.strptime()以所有数字显示日期,如:“1982-05-02”

Here's what I tried:

这是我试过的:

full_date1 = datetime.strptime(full_date, "%Y-%m-%d")

When I try to print this, I get garbage values like built-in-67732 Where am I going wrong? Does the strptime() method not accept string values?

当我尝试打印这个时,我得到了内置67732的垃圾值我在哪里出错了? strptime()方法不接受字符串值吗?

1 个解决方案

#1


Your format string is wrong, it should be this:

你的格式字符串是错误的,它应该是这样的:

In [65]:

full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)

You then need to call strftime on a datetime object to get the string format you desire:

然后,您需要在datetime对象上调用strftime以获取所需的字符串格式:

In [67]:

dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'

strptime is for creating a datetime format from a string, not to reformat a string to another datetime string.

strptime用于从字符串创建日期时间格式,而不是将字符串重新格式化为另一个日期时间字符串。

So you need to create a datetime object using strptime, then call strftime to create a string from the datetime object.

所以你需要使用strptime创建一个datetime对象,然后调用strftime从datetime对象创建一个字符串。

The datetime format strings can be found in the docs as well as an explanation of strptime and strftime

日期时间格式字符串可以在文档中找到,也可以在strptime和strftime中找到

#1


Your format string is wrong, it should be this:

你的格式字符串是错误的,它应该是这样的:

In [65]:

full_date = "May.02.1982"
import datetime as dt
dt.datetime.strptime(full_date, '%b.%d.%Y')
Out[65]:
datetime.datetime(1982, 5, 2, 0, 0)

You then need to call strftime on a datetime object to get the string format you desire:

然后,您需要在datetime对象上调用strftime以获取所需的字符串格式:

In [67]:

dt.datetime.strptime(full_date, '%b.%d.%Y').strftime('%Y-%m-%d')
Out[67]:
'1982-05-02'

strptime is for creating a datetime format from a string, not to reformat a string to another datetime string.

strptime用于从字符串创建日期时间格式,而不是将字符串重新格式化为另一个日期时间字符串。

So you need to create a datetime object using strptime, then call strftime to create a string from the datetime object.

所以你需要使用strptime创建一个datetime对象,然后调用strftime从datetime对象创建一个字符串。

The datetime format strings can be found in the docs as well as an explanation of strptime and strftime

日期时间格式字符串可以在文档中找到,也可以在strptime和strftime中找到