WHAT IS DATETIME MODULE IN PYTHON?

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
DirectiveDescriptionOutput
%aWeekday, short versionSun
%AWeekday, full versionSunday
%wWeekday as a number 0-6, 0 is Sunday0
%dDay of month 01-3123
%bMonth name, short versionApr
%BMonth name, full versionApril
%mMonth as a number 01-124
%yYear, short version, without century23
%YYear, full version2023
%HHour 00-232
%IHour 00-122
%pAM/PMAM
%MMinute 00-5932
%SSecond 00-593
%fMicrosecond 000000-9999993
%zUTC offset100
%ZTimezoneCST
%jDay number of year 001-366113
%UWeek number of year, Sunday as the first day of week, 00-5321
%WWeek number of year, Monday as the first day of week, 00-5322
%cLocal version of date and timeSun Apr 23 02:32:03 2023
%CCentury20
%xLocal version of date04/23/23
%XLocal version of time02:35:20
%%A % character%
%GISO 8601 year2023
%uISO 8601 weekday (1-7)7
%VISO 8601 weeknumber (01-53)16

Directive for datetime format in Python


Posted

in

Tags:

Comments

Leave a Reply