截断一个python datetime对象的经典方法是什么?

在这种特殊情况下,到今天为止。基本上就是将小时,分,秒,微秒设置为0。

我希望输出也是一个datetime对象,而不是字符串。


当前回答

如果你想截断一个任意的timedelta:

from datetime import datetime, timedelta
truncate = lambda t, d: t + (datetime.min - t) % - d
# 2022-05-04 15:54:19.979349
now = datetime.now()

# truncates to the last 15 secondes
print(truncate(now, timedelta(seconds=15)))
# truncates to the last minute
print(truncate(now, timedelta(minutes=1)))
# truncates to the last 2 hours
print(truncate(now, timedelta(hours=2)))
# ...

"""
2022-05-04 15:54:15
2022-05-04 15:54:00
2022-05-04 14:00:00
"""

PS:这是针对python3的

其他回答

详见https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html

现在是2019年,我认为最有效的方法是:

df['truncate_date'] = df['timestamp'].dt.floor('d')

有一个模块datetime_truncate为您处理这个问题。它只调用datetime。replace。

6年后……我发现了这篇文章,我更喜欢numpy方法:

import numpy as np
dates_array = np.array(['2013-01-01', '2013-01-15', '2013-01-30']).astype('datetime64[ns]')
truncated_dates = dates_array.astype('datetime64[D]')

干杯

有一个用来处理日期的很棒的库:Delorean

import datetime
from delorean import Delorean
now = datetime.datetime.now()
d = Delorean(now, timezone='US/Pacific')

>>> now    
datetime.datetime(2015, 3, 26, 19, 46, 40, 525703)

>>> d.truncate('second')
Delorean(datetime=2015-03-26 19:46:40-07:00, timezone='US/Pacific')

>>> d.truncate('minute')
Delorean(datetime=2015-03-26 19:46:00-07:00, timezone='US/Pacific')

>>> d.truncate('hour')
Delorean(datetime=2015-03-26 19:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('day')
Delorean(datetime=2015-03-26 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('month')
Delorean(datetime=2015-03-01 00:00:00-07:00, timezone='US/Pacific')

>>> d.truncate('year')
Delorean(datetime=2015-01-01 00:00:00-07:00, timezone='US/Pacific')

如果你想要返回datetime值:

>>> d.truncate('year').datetime
datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
>>> import datetime
>>> dt = datetime.datetime.now()
>>> datetime.datetime.date(dt)
datetime.date(2019, 4, 2)