Search code examples
pythonpython-3.xdatetimepython-datetime

How to convert a datetime to a string as shown?


using python 3.9

I want to create a program that instead of printing 2/28/2021, it prints Sunday, 2, Feb, 2021.


Solution

  • You can do it using strptime() to achieve a human-readable string.

    import datetime
    a = datetime.datetime.now()
    print(a.strftime("%a, %d, %B, %Y")) # Sun, 28, February, 2021
    print(a.strftime("%A, %d, %B, %Y")) # Sunday, 28, February, 2021
    
    import locale
    locale.setlocale(locale.LC_TIME, "sv_SE") # swedish locale
    print(a.strftime("%a, %d, %B, %Y")) # sön, 28, februari, 2021