Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python datetime-在使用strTime获取日、月、年后设置固定的小时和分钟_Python_Date_Datetime_Time_Date Manipulation - Fatal编程技术网

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

Python datetime-在使用strTime获取日、月、年后设置固定的小时和分钟,python,date,datetime,time,date-manipulation,Python,Date,Datetime,Time,Date Manipulation,我已成功地将2012年9月26日的26格式转换为26-09-2012格式,使用: datetime.strtime(request.POST['sample_date','%d%b%Y') 然而,我不知道如何将上述事件的时间和分钟设置为11:59。有人知道怎么做吗? 请注意,这可以是未来日期或任意随机日期,而不仅仅是当前日期。使用: 将提供最佳选择。此外,它还提供了替换日、年和月的功能 假设我们有一个datetime对象,日期表示为: “2017-05-04” 如果将日期作为datetime.d

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

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

然而,我不知道如何将上述事件的时间和分钟设置为11:59。有人知道怎么做吗?

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

使用:

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

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


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

导入日期时间
dt=datetime.datetime(2020,7,1)
t=datetime.time(12,34)
combined=datetime.datetime.combined(dt.date(),t)

感谢您的快速回复!:)只是好奇有没有一种不用额外的日期变量的方法?(我是python新手)是的,只需执行
date=datetime.strtime('2012年9月26日','%d%b%Y')。替换(小时=11,分钟=59)
。我使用了额外的变量,因此行不会太长:)也值得注意:
datetime.replace
返回日期时间的新副本(因为
datetime
是不可变的):这就像是
str.replace
那样。我如何删除'2016-06-01'之后的所有内容,以使小时-分钟和秒消失?@PV8如果您想要日期时间,请运行:
r=dt.replace(小时=0,分钟=0,秒=0,微秒=0)
。如果您想要一个日期对象,请运行:
r=dt.date()
您的答案相对于您的答案早5年发布的NNONNEO的答案有什么附加值?
from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)
>>> 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