I have a Python datetime.datetime
object. What is the best way to subtract one day?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You can use a timedelta object:
Also just another nice function i like to use when i want to compute i.e. first/last day of the last month or other relative timedeltas etc. ...
The relativedelta function from dateutil function (a powerful extension to the datetime lib)
If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons):
In general,
day_ago
andyesterday
may differ if UTC offset for the local timezone has changed in the last day.For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M. in America/Los_Angeles timezone therefore if:
then
day_ago
andyesterday
differ:day_ago
is exactly 24 hours ago (relative tonow
) but at 11 am, not at 10 am asnow
yesterday
is yesterday at 10 am but it is 25 hours ago (relative tonow
), not 24 hours.pendulum
module handles it automatically:Just to Elaborate an alternate method and a Use case for which it is helpful:
It can similarly be used with other parameters e.g. seconds, weeks etc
Subtract
datetime.timedelta(days=1)
Genial arrow module exists
output: