+ 2

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

21st May 2020, 10:19 AM
Karina Matuszek
Karina Matuszek - avatar
7 ответов
+ 6
You can use: print(today_.month) # output: 5 or: print(today_.strftime("%-m")) # output: 5
21st May 2020, 11:25 AM
Lothar
Lothar - avatar
+ 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.
21st May 2020, 10:59 AM
Lothar
Lothar - avatar
+ 3
Thank you for your help on that😊
22nd May 2020, 8:43 AM
Karina Matuszek
Karina Matuszek - avatar
+ 2
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?
21st May 2020, 11:07 AM
Karina Matuszek
Karina Matuszek - avatar
+ 2
Hey, thats exactly what I was looking for! Excellent!! Thank you!
21st May 2020, 11:31 AM
Karina Matuszek
Karina Matuszek - avatar
+ 1
Code Crasher I actually didn’t come across f-strings before. It looks very convenient! Thank you😊
21st May 2020, 4:02 PM
Karina Matuszek
Karina Matuszek - avatar
+ 1
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?
22nd May 2020, 8:28 AM
Karina Matuszek
Karina Matuszek - avatar