Converting date in Python using datetime module
Is there a way to convert date using datetime module to output single digit day or month (using datetime.strptime and datetime.strftime)?
You can use: print(today_.month) # output: 5 or: print(today_.strftime("%-m")) # output: 5
You can do this by using strftime(), that can use format specifiers: import datetime now_ = datetime.datetime.now() print(now_.strftime("Current Time: %I:%M:%S")) today_ = datetime.date.today() print("Today's Date:", today_) print(today_.strftime("Current Day: %a - %A -%d - %w ")) print(today_.strftime("Current Month: %b - %B - %m")) The result of this code is: Current Time: 01:00:14 Today's Date: 2020-05-21 Current Day: Thu - Thursday -21 - 4 Current Month: May - May - 05 It is also possible to do this: print(today_.day, today_.month) # output: 21 5 The format specifiers can be found in the python docs: https://docs.python.org/3.7/library/datetime.html You have to go to the very bottom of this page.
Thank you for your help on that😊
Thank you for your answer, but your code returns double digit number for both day and month. I was playing with strftime conversion and I’m familiar with those format specifiers. My challenge was can you use this module to convert to single digit output. In the example you provided, can you convert May to 5 without zero in front?
Hey, thats exactly what I was looking for! Excellent!! Thank you!
Code Crasher I actually didn’t come across f-strings before. It looks very convenient! Thank you😊
Code Crasher That’s great! So in the second statement %s is any string format specifier and %d is a number format specifier? F-string has the easiest syntax! Are there any differences/restrictions between the 3 at all?