我有个连线问题。
from datetime import datetime, timedelta
start_date = '2019-05-01'
end_date = '2020-04-30'
start_date = datetime.strptime(start_date, "%Y-%m-%d")
print(start_date)
new_start_date = (datetime.strptime(end_date, '%Y-%m-%d') - timedelta(days=360)).strftime('%Y-%m-%d')
print(new_start_date)
回报是
2019-05-01 00:00:00
2019-05-06
看起来,第一个"start_date“包含日期和时间,第二个"new_start_date”只包含日期。为什么?我怎样才能改变让第一个"start_date“只返回日期,没有时间?
发布于 2020-09-04 03:30:08
strptime
返回一个datetime
对象。文档
类方法datetime.strptime(date_string,format) 返回与date_string对应的日期时间,按格式解析。
其中,strftime
返回由格式化字符串指定的字符串。文档
Date.strftime(格式) 返回由显式格式字符串控制的表示日期的字符串。引用小时、分钟或秒的格式代码将看到0值。有关格式化指令的完整列表,请参见strftime()和strptime()行为。
在你的例子中;
datetime.strptime(start_date, "%Y-%m-%d") #2019-05-01 00:00:00
然而,如果您要使用strftime
来格式化这一点,它将继续删除时间;
datetime.strptime(start_date, "%Y-%m-%d").strftime('%Y-%m-%d')) #2019-05-01
发布于 2020-09-04 03:30:01
new_start_date
不是date
,它是string
。您可以删除strftime
以获取datetime
对象。
https://stackoverflow.com/questions/63734382
复制相似问题