Converting Time Format without using strptime

Question:

I’ve been tasked with printing yesterday’s, today’s and tomorrow’s date. The task itself is very simple, but i wanted to also change the way the date is displayed. I would like to display the date as day/month/year

I’ve tried the ways proposed online but they don’t work for me, fex. strptime apparently cannot be an attribute for datetime whenever i try doing it.

below is my code so far with the broken bits taken out again.

#data is imported from module
import datetime 
#today defined as the value assigned to current day
today = datetime.date.today()
#yesterday calculated by subtracting 'one day'. .timedelta() is used to go back 1 day. just subtracting one would allow for invaldid dates. such as the 0th of a month
yesterday = today - datetime.timedelta(days = 1)
#.timedelta() used to avoid displayng an invalid date such as the 32nd of a month. 1 day is added to define the variable 'tomorrow'
tomorrow = today + datetime.timedelta(days = 1) 

#here the variables are printed 
print("Yesterday : ", yesterday)
print("Today : ", today)
print("Tomorrow : ", tomorrow)
Asked By: freen

||

Answers:

I’m not sure why you don’t want to use strftime, but if you absolutely wanted a different way, try altering your last three lines to this:

print(f"Yesterday : {yesterday.day}/{yesterday.month}/{yesterday.year}")
print(f"Today : {today.day}/{today.month}/{today.year}")
print(f"Tomorrow : {tomorrow.day}/{tomorrow.month}/{tomorrow.year}")

which produces:

Yesterday : 9/11/2022
Today : 10/11/2022
Tomorrow : 11/11/2022

You could make it a little more compact like this:

days = {'yesterday' : yesterday, 'today' : today, 'tomorrow' : tomorrow}

for daystr, day in days.items():
    print (f"{daystr.title()} : {day.day}/{day.month}/{day.year}")
Answered By: Vineet
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.