240

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

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?

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

4

4 回答 4

483

使用datetime.replace

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

另外值得注意的是:datetime.replace返回一个新的副本datetime(因为datetime是不可变的):在这方面就像str.replace

于 2012-09-18T00:28:24.963 回答
59

datetime.replace()将提供最佳选择。此外,它还提供了替换日、年和月的功能。

假设我们有一个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
于 2017-05-12T08:48:53.533 回答
12

如果您将日期作为datetime.datetime(或datetime.date)实例并希望通过datetime.time实例中的时间将其组合,则可以使用 classmethod datetime.datetime.combine

import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)
于 2020-07-27T08:14:05.170 回答
0

将日期时间转换为最大值或最小值的快捷方式

import datetime

def dt_time_min(dt):
    """converts any datetime/date to new datetime with same date and time=0:00:00"""
    return datetime.datetime.combine(dt, datetime.time.min)


def dt_time_max(dt):
    """converts any datetime/date to new datetime with same date and time=23:59:59.999999"""
    return datetime.datetime.combine(dt, datetime.time.max)
于 2021-10-14T06:31:33.687 回答