Python Datetime Module
Python Datetime Module in Python provides us the different features to work with dates as date object by importing the datetime module.
Current Date
Python code to import the datetime module to access current date
import datetime
x = datetime.datetime.now()
print(x)
output
(Note-it will show the current date and time, at the time of execution of code on your machine)
2023-04-23 02:04:40.668286
The date format contains year, month, day, hour, minute, second, and microsecond.
Python code to return the year and name of the weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Output
2023
Sunday
Creating Date Objects in Python
We can use the datetime() class (constructor) of the datetime module to create a date.
The datetime() class requires three parameters to create a date: year, month, day.
Python to create a date object
import datetime
x = datetime.datetime(2023, 4, 23)
print(x)
output
2023-04-23 00:00:00
note- 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 in Python datetime module
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:
Python code to display the name of the month:
import datetime
x = datetime.datetime(2023, 4, 23)
print(x.strftime("%B"))
Output
April
Python code syntax, to show the output for different <directive> provided in below table-
Syntax:
import datetime
x = datetime.datetime.now()
print(x.strftime("<Directive>")) #use directive from table
Directive | Description | Output |
%a | Weekday, short version | Sun |
%A | Weekday, full version | Sunday |
%w | Weekday as a number 0-6, 0 is Sunday | 0 |
%d | Day of month 01-31 | 23 |
%b | Month name, short version | Apr |
%B | Month name, full version | April |
%m | Month as a number 01-12 | 4 |
%y | Year, short version, without century | 23 |
%Y | Year, full version | 2023 |
%H | Hour 00-23 | 2 |
%I | Hour 00-12 | 2 |
%p | AM/PM | AM |
%M | Minute 00-59 | 32 |
%S | Second 00-59 | 3 |
%f | Microsecond 000000-999999 | 3 |
%z | UTC offset | 100 |
%Z | Timezone | CST |
%j | Day number of year 001-366 | 113 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 21 |
%W | Week number of year, Monday as the first day of week, 00-53 | 22 |
%c | Local version of date and time | Sun Apr 23 02:32:03 2023 |
%C | Century | 20 |
%x | Local version of date | 04/23/23 |
%X | Local version of time | 02:35:20 |
%% | A % character | % |
%G | ISO 8601 year | 2023 |
%u | ISO 8601 weekday (1-7) | 7 |
%V | ISO 8601 weeknumber (01-53) | 16 |
Directive for datetime format in Python
Leave a Reply