Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

Generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python date module

What is python date module?

We can generate or create dates and times in python using the date module. The date is a module by which we can work with date and time in python.

Because it is a module, so we have to import it into the python file if we want to work with it.
To import write:
import datetime

date() function

Let's see an example: In this example, we will create a date using the date function.
Function parameters:
date(year, month, data)

Be careful about one thing:
If the digit is single then don't use 0 before the digit. If we use zero then it will give an error.

We can also extract particular information from here like, only day, month, year, weekday.

To get weekday we use the weekday() function. In this function index number starts from Monday end to Sunday. Monday index number is 0 and Sunday index number is 6.

Example:
Input
import datetime

x = datetime.date(2022, 3, 14)
print('full date:',x)

print("only year is:",x.year)
print("only month is:",x.month )
print("only day is:",x.day)
print("only weekday is:",x.weekday())
Output
full date: 2022-03-14

only year is: 2022
only month is: 03
only day is: 14
only weekday is: 0

Date class methods


Function Description
weekday() This function returns the day of the week in numeric form. Here Monday is 0 and Sunday is 6
ctime() This function returns a string representing the date
today() This function returns the current local date
replace() This function changes the value of the date object with the given parameter
fromisocalendar() This function returns a date according to the ISO calendar
isocalendar() This function returns a date according to the ISO calendar

time() function

time() function is used to create time.
parameters:
time(hour, minute, second, microsecond)

Be careful about one thing:
If the digit is single then don't use 0 before the digit. If we use zero then it will give an error.

We can also extract a particular information from here like, only hour, second , microsecond, minute. It means if we don't pass values for time then we will see 00:00:00 in the output.

Time class methods


Function Description
dst() This function returns tzinfo.dst() is tzinfo is not None
isoformat() This function returns the time into string
fromisoformat() This function returns a time object from the string representation or format of the time
replace() This function changes the value of the time object with the given parameter

Example:
Input
import datetime

x = datetime.time(4, 3, 14)
print('full time:',x)
print("only minute is:",x.min)
print("only second is:",x.second )
print("only hour is:",x.hour)
print("only microsecond is:",x.microsecond)

Output
only date: 2022-03-14 00:00:00
only year is: 2022
only month is: 03
only day is: 14
only weekday is: 0
date with time: 2022-03-14 04:20:44

datetime() function

By using the date function we can only create a date and using the time function we can only create time. But in datetime function we can create both date and time.
Parameters:
datetime(year, month, day, hour, hour, minute, second, microsecond )

Be careful about one thing:
If the digit is single then don't use 0 before the digit. If you use zero then it will give an error.

We can also extract particular information from here like, only day, month, year, weekday, hour, second, microsecond, minute and if we don't pass values for time then you will see 00:00:00 in the output.

Example:
Input
import datetime

x = datetime.datetime(2020, 5, 17, 4, 20, 44)
print('date and time:',x)

print("only year is:",x.year)
print("only month is:",x.month )
print("only day is:",x.day)
print("only weekday is:",x.weekday())

print("only minute is:",x.min)
print("only second is:",x.second )
print("only hour is:",x.hour)
Output
date with time: 2022-03-14 04:20:44

only year is: 2022
only month is: 05
only day is: 17
only weekday is: 5
only hour is: 04
only second is: 44
only minute is: 20

Date Time class methods


Function Description
fromisoformat() This function returns a datetime object from the date time string
isocalendar() This function returns a tuple year, week, and weekday
astimezone() This function returns the DateTime object containing timezone information.
date() This function returns the Date class object
tzname() This function returns the name of the time zone
time() This function returns time class object
now() This function returns current local date
weekday() This function returns the weekdays in the numeric form. Here monday stars from 0 and sunday is 6
utcnow() This function returns the current UTC date and time
combine() This function return a combine(separate date and time) DateTime object

today() function

To see current date we will use today() function.

Example:1
Input
import datetime

tday = datetime.date.today()
print("today full date is:",tday)
Output
today full date is: 2022-02-04

Here today function will display the today's date.

We can also extract a particular information from here like, only day, month, year, weekday.

To get weekday we use the weekday() function. In this function index number starts from Monday end to Sunday. Monday index number is 0 and Sunday index number is 6.

Example:2
Input
import datetime

tday = datetime.date.today()
print("today full date is:",tday)
print("today year is:",tday.year)
print("today month is:",tday.month )
print("today day is:",tday.day)
print("today weekday is:",tday.weekday())
Output
today full date is: 2022-02-04
today year is: 2022
today month is: 02
today day is: 04
today weekday is: 5

now() function

To see the current date and time we will use the now() function.

Example:
Input
import datetime

tday = datetime.datetime.now()
print("today full date and time is:",tday)
Output
today full date and time is:today full date and time is: 2022-04-02 06:51:38.719341

Date formatting

In the datetime of today function, we got a date and the date format is year-month-day. If we want to change the format then we can do that.
To do this we use the strftime() function. In this function, we will pass the format code and according to the given format, the date will be formatted.

Let's see the date format codes :


Directive Description Example
%d Used to get day of the month 01-31 20
%b Used to get month name short version Mar
%B Used to get month name full version March
%m Used to get month in the form of number 01-12 03
%w Used tog get weekday as a number(0-6) like 1 is Monday 5
%y Used to get year short version without century 22
%Y Used to get year full version 2022
%a Used to get weekday, short version Fri
%A Used to get weekday, full version Friday
%H Used to get hour from 00-23 19
%I Used to get hour from 00-12 11
%p Used to get AM/PM AM
%M Used to get minute 00-59 30
%S Used to get second 00-59 16
%H Used to get hour from 00-23 19
%I Used to get hour from 00-12 11
%f Used to get Microsecond 000000-999999 237522
%Z Used to get timezone CST
%z UTC offset +0200
%U Used to get week number of the year.Here sunday is the first day of the week and total number of week is 0-53 10
%j Used to get day number of year 001-366 100
%y Used to get year short version without century 22
%Y Used to get year full version 2022
%c Used to get local version of date and time Mon Mar 03 11:20:00 2022
%X Used to get local version of time 12:21:00
%x Used to get local version of date 03/14/22
%C Used to get century 20

Example:
Input
import datetime x = datetime.date(2022, 3, 14)

print("Month name full version:",x.strftime("%B"))
print("Weekday short version:",x.strftime("%a"))
print("Day of month:",x.strftime("%d"))
print("Year full version:",x.strftime("%Y"))
print("Hour:",x.strftime("%I"))
Output
Month name full version: March
Weekday short version: Mon
Day of month: 14
Year full version: 2022
Hour: 04

Convert date into string

To convert date into string isoformat() function is used.

Example:
Input
import datetime

tday = datetime.date.today()

Str = datetime.date.isoformat(tday)
print("String format", Str)
print(type(Str))
Output
String Representation 2022-04-02
<class 'str'>

Timedelta class

This timedelta class is used for calculating differences between dates. We can also use it for date manipulations.

Parameter:
class datetime.timedelta(days=int_val, seconds=int_val, microseconds=int_val, milliseconds=int_val, minutes=int_val, hours=int_val, weeks=int_val)

Example 1:
Input
import datetime

# Let's use Using current time
currTime = datetime.datetime.now()

# printing the current date
print("current time", str(currTime))

'''
Calculating future dates
for three years
'''
date_after_3_years = currTime + datetime.timedelta(days=1095)

date_after_3days = currTime + datetime.timedelta(days=3)

# printing calculated future_dates
print('date_after_3_years:', str(date_after_3_years))
print('date_after_3days:', str(date_after_3days))
Output
current time 2022-04-02 09:23:08.071013
date_after_3_years: 2025-04-01 09:23:08.071013
date_after_3days: 2022-04-05 09:23:08.071013

Let's find difference between date and time

Example:
Input
import datetime

currTime = datetime.datetime.now()

print("currTime", str(currTime))

new_time = currTime + \ datetime.timedelta(days=3)

print("new_time", str(new_time))

print('Time difference:', str(new_time - currTime))
Output
currTime 2022-04-02 09:36:55.217511
new_time 2022-04-05 09:36:55.217511
Time difference: 3 days, 0:00:00

Operators for Timedelta

Operator Description
Addition (+) Returns two timedelta objects by doing addition
Division (/) Divides the timedelta object with float or int
Multiplication (*) Returns two timedelta objects with float or int by doing Multiplication
Subtraction (-) Returns two timedelta objects by doing Subtraction

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.