Python Forum
How to print n days back date at give time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print n days back date at give time
#1
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'
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 116 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Date Time Series Help...Please spra8560 2 312 Feb-01-2024, 01:38 PM
Last Post: spra8560
  Python date format changes to date & time 1418 4 514 Jan-20-2024, 04:45 AM
Last Post: 1418
  Downloading time zone aware files, getting wrong files(by date))s tester_V 9 959 Jul-23-2023, 08:32 AM
Last Post: deanhystad
  Formatting a date time string read from a csv file DosAtPython 5 1,160 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Print names in x-axis of a time-series values hobbyist 4 1,177 Apr-22-2023, 09:29 PM
Last Post: deanhystad
  Return the [Date] that within the last 14 days bnadir55 5 1,127 Dec-08-2022, 03:38 PM
Last Post: snippsat
  Give visit number ( or counter) within the same time frame balthordu 1 913 Jun-27-2022, 09:51 AM
Last Post: Larz60+
  How split N days between specified start & end days SriRajesh 2 1,302 May-06-2022, 02:12 PM
Last Post: SriRajesh
  Wait til a date and time KatManDEW 2 1,390 Mar-11-2022, 08:05 PM
Last Post: KatManDEW

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020