Home > other >  Transforming the current date and getting the date 7 days earlier
Transforming the current date and getting the date 7 days earlier

Time:10-05

I need to transform dates to this format:

#(Optional) Start date in format YYYY-MM-DD HH:NN:SS.

To make api call and then get from it date 7 days earlier

from datetime import datetime, timedelta    

end = datetime.now().strftime("%Y-%m-%d% %H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start )
print("End: ", end )

I tried to do it this way but I get an error

unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

CodePudding user response:

Thanks to Peter Wood i fixed this silly mistake

end_time = datetime.now()
start_time = end_time - timedelta(days=7)
end = end_time.strftime("%Y-%m-%d% %H:%M:%S")
start = start_time.strftime("%Y-%m-%d% %H:%M:%S")
print("Start: ", start )
print("End: ", end )

CodePudding user response:

With strftime you are casting end to string, remove that part like this:

from datetime import datetime, timedelta

end = datetime.now()#.strftime("%Y-%m-%d% %H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start)
print("End: ", end)

If you want to format your output you can then add .strftime("%Y-%m-%d% %H:%M:%S") like this:

from datetime import datetime, timedelta

end = datetime.now()#.strftime("%Y-%m-%d% %H:%M:%S")
start = end - timedelta(days=7)
print("Start: ", start.strftime("%Y-%m-%d% %H:%M:%S"))
print("End: ", end.strftime("%Y-%m-%d% %H:%M:%S"))

CodePudding user response:

from datetime import datetime, timedelta
from urllib.parse import quote

end = datetime.now()
start = end - timedelta(days=7)
print("Start: ", quote(start.strftime("%Y-%m-%d %H:%M:%S")))
# Start:  2022-09-27 08:28:11
  • Related