In this article, let us see how to use datetime package in Python and how to generate current date in different formats like the following
- YYYY-MM-DD
- MM-YYYY-DD
- DD-MM-YYYY
The first step is to import the datetime
package, by giving from datetime import date then call the method date.today()
which gives the current date as a result and the default format is YYYY-MM-DD
date in YYYY-MM-DD
from datetime import date
date = date.today()
print("Date: ", date)
Output:
Date: 2020-11-28
If we wish to get the current date in other formats i.e. other than YYYY-MM-DD formats then we could do so, by following the below methods.
datetime.strftime() method is used to format the dates in Python, let’s generate the date in different format.
date in MM-YY-DD:
from datetime import date
date = date.today()
type2 = date.strftime("%m-%y-%d")
print("Date: ", type2)
Output:
Date: 11-20-28
Here, we are using .strf time() allows us to modify or mention the format specifiers for a date object. This method must be used if we want to print the current date in different formats.
date in DD-MM-YYYY:
from datetime import date
date = date.today()
type3 = date.strftime("%d-%m-%y")
print("Date: ", type3)
Output:
Date: 28-11-2020
References:
Happy Learning 🙂