Display various Datetime formats using Python
In this tutorial, we will see how to display various datetime formats in Python using simple methods.
Datetime library in Python
As the name suggests, the datetime formats in Python can be easily displayed using the datetime library. To install the library you can use the following command on your command prompt.
pip install datetime
Now that you have installed datetime, import it as dt using this command
import datetime as dt print('Datetime imported as dt')
datetime imported as dt
So now that we have successfully installed and imported the library, let us start printing the various datetime formats. First, we will display the current time date and time.
print("Current date and time: " , dt.datetime.now())
Output: Current date and time: 2020-03-26 12:32:07.942730
Here we can see that by using the datetime.now() method, the current date and time have been displayed. Similarly, using built-in datetime methods, we can display various other formats.
Current month and year
print("Current year: ", dt.date.today().strftime("%Y")) print("Month of year: ", dt.date.today().strftime("%B"))
Output: Current year: 2020 Month of year: March
Current week of the year and weekday
print("Week number of the year: ", dt.date.today().strftime("%W")) print("Weekday of the week: ", dt.date.today().strftime("%w"))
Output: Week number of the year: 12 Weekday of the week: 4
Day of year, Day of the month, Day of week
print("Day of year: ", dt.date.today().strftime("%j")) print("Day of the month : ", dt.date.today().strftime("%d")) print("Day of week: ", dt.date.today().strftime("%A"))
Output: Day of year: 086 Day of the month : 26 Day of week: Thursday
So, we have seen how to display various datetime formats using datetime library in Python.
Also read: Python Date and Time
Get the current date and time in every possible format in Python
Leave a Reply