Python datetime - 在使用strptime获取日,月,年之后设置固定的小时和分钟

时间:2023-02-09 20:24:33

I've successfully converted something of 26 Sep 2012 format to 26-09-2012 using:

我已成功将2012年9月26日格式转换为26-09-2012,使用:

datetime.strptime(request.POST['sample_date'],'%d %b %Y')

datetime.strptime(request.POST ['sample_date'],'%d%b%Y')

However, I don't know how to set the hour and minute of something like the above to 11:59. Does anyone know how to do this?

但是,我不知道如何将上述的时间和分钟设置为11:59。有谁知道如何做到这一点?

Note, this can be a future date or any random one, not just the current date.

请注意,这可以是将来的日期或任何随机日期,而不仅仅是当前日期。

2 个解决方案

#1


222  

Use datetime.replace:

使用datetime.replace:

from datetime import datetime
date = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdate = date.replace(hour=11, minute=59)

#2


16  

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

datetime.replace()将提供最佳选择。此外,它还提供更换日,年和月的工具。

Suppose we have a datetime object and date is represented as: "2017-05-04"

假设我们有一个datetime对象,日期表示为:“2017-05-04”

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59

#1


222  

Use datetime.replace:

使用datetime.replace:

from datetime import datetime
date = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdate = date.replace(hour=11, minute=59)

#2


16  

datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.

datetime.replace()将提供最佳选择。此外,它还提供更换日,年和月的工具。

Suppose we have a datetime object and date is represented as: "2017-05-04"

假设我们有一个datetime对象,日期表示为:“2017-05-04”

>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59