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
  Print names in x-axis of a time-series values hobbyist 4 657 Apr-22-2023, 09:29 PM
Last Post: deanhystad
  Return the [Date] that within the last 14 days bnadir55 5 519 Dec-08-2022, 03:38 PM
Last Post: snippsat
  Give visit number ( or counter) within the same time frame balthordu 1 487 Jun-27-2022, 09:51 AM
Last Post: Larz60+
  How split N days between specified start & end days SriRajesh 2 862 May-06-2022, 02:12 PM
Last Post: SriRajesh
  Wait til a date and time KatManDEW 2 963 Mar-11-2022, 08:05 PM
Last Post: KatManDEW
  Date format and past date check function Turtle 5 2,243 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  Print first day of the week as string in date format MyerzzD 2 1,560 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  How to print results of asyncio websockets at the same time? codingmonster 0 1,502 Jun-04-2021, 01:48 PM
Last Post: codingmonster
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 1,778 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Naming the file as time and date. BettyTurnips 3 2,102 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips

Forum Jump:

User Panel Messages

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