Python Forum

Full Version: How to print n days back date at give time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I want to print "N" days back date with specified time. I use below code but it error:

from datetime import datetime, timedelta
Quote:N = 2
date_N_days_ago = datetime.now().strftime("%Y-%M-%D 07:20:00") - timedelta(days=N)

print(datetime.now())
print(date_N_days_ago)

error is below:

TypeError Traceback (most recent call last)
<ipython-input-3-5b8535c0ec9c> in <module>()
3 N = 2
4
----> 5 date_N_days_ago = datetime.now().strftime("%Y-%M-%D 07:20:00") - timedelta(days=N)
6
7 print(datetime.now())

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
strftime() turns it into a string.  Do that only at the end, not before the math is done.


from datetime import datetime, timedelta
N = 2
date_N_days_ago = datetime.now() - timedelta(days=N)

print(datetime.now())
print(date_N_days_ago)
print(date_N_days_ago.strftime("%Y-%m-%d 07:20:00"))
Output:
2020-10-09 20:34:03.536442 2020-10-07 20:34:03.536418 2020-10-07 07:20:00