Home > Net >  how to get D instated of DD from DD-MM-YYYY format if day = 01 to 09 then output should be 1 to 9
how to get D instated of DD from DD-MM-YYYY format if day = 01 to 09 then output should be 1 to 9

Time:01-01

Output I got = January 01, 2023

But required Output = January 1, 2023

import datetime
import tkinter as tk
from tkcalendar import DateEntry
root = tk.Tk()
root.geometry("380x220")
midate = datetime.date(2020,1,1)
cal1 = DateEntry(root, selectmode='day')
cal1.grid(row=1, column=1, padx=20, pady=30)

def my_upd():
print(cal1.get_date().strftime("%B %d, %Y"))

b1 = tk.Button(root, text='Read', command=lambda:my_upd())
b1.grid(row=2, column=1)

root.mainloop()

CodePudding user response:

It seems strange that there's no format code for a non-padded day of the month. But you can put it together piece wise and remove the leading zero.

d = cal1.get_date()
print(d.strftime("%B ")   d.strftime("%d").lstrip("0")   d.strftime(", %Y"))

You could do the same thing and not bother with strftime for the day:

print(d.strftime("%B ")   str(d.day)   d.strftime(", %Y"))

CodePudding user response:

Even if you go to the official python documentation, you will not find any formatting for day without leading zeros.

The only way you can remove these zeros is by simply using python's replace() string method.

import datetime

midate = datetime.date(2020,1,1)

def my_upd():
    print(midate.strftime("%B %d, %Y").replace(' 0', ' '))

my_upd()

Output:

January 1, 2020

Some platforms will support %e, but if your application wants to run in all circumstances, you will have to follow the safe steps.

CodePudding user response:

This question has been answered in the link below. Python strftime - date without leading 0?

If you want to get detailed information about Python date formatting, I recommend you to look at the following document.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

  • Related