Python Date and time
Python Date and time
Python Datetime
=============================================
=>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.
------------------------------------------------------------------------
Examples: Import the datetime module and display the current date:
------------------------------------------------------------------------
import datetime
x = datetime.datetime.now()
print(x) # 2024-11-07 07:27:06.886118
The date contains year, month, day, hour, minute, second, and microsecond.
------------------------------------------------------------------------
Example: Return the year and name of weekday:
------------------------------------------------------------------------
import datetime
x = datetime.datetime.now() # Here x is an object of <class 'datetime.datetime'>
print(x.year) # 2024
print(x.strftime("%A")) #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.
--------------------------------------------------------------------------
Example: Create a date object:
--------------------------------------------------------------------------
import datetime
x = datetime.datetime(2020, 5, 17)
print(x) # 2020-05-17 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:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B")) # June
**************************************************************************************
A reference of all the legal format codes:
**************************************************************************************
Format Description Example
-------------------------------------------------------------------------------------------------------
%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
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%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
%C Century 20
%x Local version of date 12/31/18
%X Local version of time 17:41:00
%u ISO 8601 weekday (1-7) 1
%V ISO 8601 weeknumber (01-53) 01
**************************************************************************************
Calculating the Difference Between Two Dates in Python
--------------------------------------------------------------------------------------
Calculating the difference between two dates is a common requirement in programming, essential for
tracking project durations, scheduling events, or measuring performance intervals. The Python datetime
module offers powerful tools for manipulating date and time data to meet these needs.
-----------------------------------------------------------------
Difference Between Current Time and a Specific Datetime
-----------------------------------------------------------------
To calculate the difference between the current time and a specific datetime, you first need to obtain the
current datetime using the datetime.now() method and then subtract the specific datetime from it.
---------------
Examples
---------------
from datetime import datetime
now = datetime.now()
past = datetime(2022, 4, 15, 16, 30, 0) # Example past date
difference = now - past
print(difference) # Output: 694 days, 20:57:03.762774
print(type(difference)) # Output: <class 'datetime.timedelta'>
date_str1 = "2023-08-25"
date_str2 = "2023-08-20"
Method 1: total_seconds()
-----------------------------------------------
The timedelta object, which you get from subtracting datetime objects, has a convenient method called
total_seconds(). This method neatly converts the difference (including days, seconds, and microseconds)
into a total number of seconds.
To use this, first, calculate the difference between your two datetime objects and then call total_seconds()
on the resulting timedelta.
-------------
Examples
-------------
from datetime import datetime
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)