In this article, you will learn to manipulate date and time in Python with the help of examples.
Python has a module named datetime to work with dates and times. Let’s create a few simple programs related to date and time before we dig deeper.
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
Import the datetime module and display the current date:
import datetime x = datetime.datetime.now() print(x) #Output 2019-08-01 03:22:55.008949
When we execute the code from the example above the result will be:
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Return the year and name of weekday:
import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) #OUTPUT 2019 Thursday
Creating Date Objects
To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
Create a date object:
import datetime x = datetime.datetime(2020, 8, 01) print(x) #OUTPUT 2020-08-01 00:00:00
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of
0, ( None for timezone).
The strftime() Method
The datetime object has a method for formatting date objects into readable strings. The method is called
strftime(), and takes one parameter, format , to specify the format of the returned string:
Display the name of the month:
import datetime x = datetime.datetime(2017, 10, 2) print(x.strftime("%B")) #OUTPUT October
A reference of all the legal format codes:
|%a||Weekday, short version||Wed|
|%A||Weekday, full version||Wednesday|
|%w||Weekday as a number 0-6, 0 is Sunday||3|
|%d||Day of month 01-31||31|
|%b||Month name, short version||Dec|
|%B||Month name, full version||December|
|%m||Month as a number 01-12||12|
|%y||Year, short version, without century||18|
|%Y||Year, full version||2018|
|%j||Day number of year 001-366||365|
|%U||Week number of year, Sunday as the first day of week, 00-53||52|
|%W||Week number of year, Monday as the first day of week, 00-53||52|
|%c||Local version of date and time||Mon Dec 31 17:41:00 2018|
|%x||Local version of date||12/31/18|
|%X||Local version of time||17:41:00|
|%%||A % character||%|
Please follow and like us: