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
  Give visit number ( or counter) within the same time frame balthordu 1 247 Jun-27-2022, 09:51 AM
Last Post: Larz60+
  How split N days between specified start & end days SriRajesh 2 504 May-06-2022, 02:12 PM
Last Post: SriRajesh
  Wait til a date and time KatManDEW 2 624 Mar-11-2022, 08:05 PM
Last Post: KatManDEW
  Date format and past date check function Turtle 5 1,582 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  Print first day of the week as string in date format MyerzzD 2 1,176 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  How to print results of asyncio websockets at the same time? codingmonster 0 1,280 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,539 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  Naming the file as time and date. BettyTurnips 3 1,590 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
  Update Date based on Time/String stevezemlicka 1 1,370 Jan-08-2021, 06:54 PM
Last Post: Gribouillis
  Confusion about [date]time [formatting] Mark17 0 1,165 Dec-17-2020, 07:25 PM
Last Post: Mark17

Forum Jump:

User Panel Messages

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