Python
In this tutorial we will learn about datatime module in Python.
We learned about modules in the Python - Modules tutorial. Feel free to check that out.
datetime
To work with data and time in Python we can take help of the datetime module.
To import the module we write the following.
import datetime
We can write the following Python code to display the current date and time using the datetime module.
# import module import datetime # current date time currDT = datetime.datetime.now() # output print(currDT)
The above Python code will give us the following output.
2018-10-21 04:43:58.846551
The date time is in the following format.
Year-Month-Day Hour:Minute:Second.Microsecond
datetime()
In the following Python program we are creating date object for the date 1st Jan 2000 using the datetime module.
1st Jan 2000
# import module import datetime # create date date = datetime.datetime(2000, 1, 1) # output print(date)
The above code will print the following output.
2000-01-01 00:00:00
In the following Python program we are creating a date object for the date time 1st Jan 2000 10:20:30.
1st Jan 2000 10:20:30
# import module import datetime # create date time date = datetime.datetime(2000, 1, 1, 10, 20, 30) # output print(date)
The above code will give the following output.
2000-01-01 10:20:30
strftime
We use the strftime() method to convert the date object into human readable string.
strftime()
The strftime method takes one argument, the format.
In the following Python program we are printing the current date in human readable format using the strftime method.
# import module import datetime # current time currDT = datetime.datetime.now() # output print("Day", currDT.strftime('%a')) print("Date", currDT.strftime('%d')) print("Month", currDT.strftime('%b')) print("Year", currDT.strftime('%Y')) print("Hour", currDT.strftime('%H')) print("Min", currDT.strftime('%M')) print("Sec", currDT.strftime('%S'))
The above code will give us a similar output.
Day Sun Date 21 Month Oct Year 2018 Hour 07 Min 34 Sec 58
%