3 ms·
Why do you find it difficult? >>> datetime.datetime.now() - datetime.timedelta(days=1) datetime.datetime(2012, 2, 1, 23, 33, 30, 591993)
by csytan 15y ago
Why do you find it difficult?
>>> datetime.datetime.now() - datetime.timedelta(days=1)
datetime.datetime(2012, 2, 1, 23, 33, 30, 591993)
- njharman 15y agoDoesn't do months or years. Who knows how it handles dst transitions. I can't remember for sure but I don't think you can subtract two dates and get a delta?
- csytan 15y agoMonths and years are tricky because they can consist of a variable number of days. To me, it's a better way of handling things without being ambiguous. For example, is one month from now exactly 30 days from today, or is it the next month on the same month day? It's pretty simple to do either with the datetime library. When taking into account DST, you should first convert from local time to UTC (pytz does this) before doing your calculations, then convert it back to local time if needed. And yes, you do get a delta when subtracting two dates.
- jvdh 15y agoYup, works fine if you're doing things only locally. However, if you're using timezone aware datetime objects you're out of luck, because then datetime.timedelta doesn't immediately apply. Just creating timezone aware datetime objects is really too difficult with the standard library anyway. You need to install `pytz` or create your own `datetime.tzinfo` classes just to be able to represent timezones. To top it off, if you have datetime objects with timezones and datetime objects without timezone information (*even created using utcfromtimezone()!), you can't compare them.