Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting Time Format without using strptime

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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)

>Solution :

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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading