如何在Python中截断DateTime对象上的时间? [英] How to truncate the time on a DateTime object in Python?
本文介绍了如何在Python中截断DateTime对象上的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
截断python datetime对象的经典方法是什么?
What is a classy way to way truncate a python datetime object?
在这种情况下,直到今天。因此,基本上将小时,分钟,秒和微秒设置为0。
In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0.
我希望输出也是日期时间对象,而不是字符串。
I would like the output to also be a datetime object, not a string.
推荐答案
我认为这就是您要寻找的...
I think this is what you're looking for...
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy
>>> dt
datetime.datetime(2011, 3, 29, 0, 0)
但是您真的不在乎时间的方面,那么您实际上应该只传递 date
对象...
But if you really don't care about the time aspect of things, then you should really only be passing around date
objects...
>>> d_truncated = datetime.date(dt.year, dt.month, dt.day)
>>> d_truncated
datetime.date(2011, 3, 29)
这篇关于如何在Python中截断DateTime对象上的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文