0% found this document useful (0 votes)
5 views

Date_&_Time.ipynb - Colaboratory

The document provides an overview of the Python DateTime module, detailing its six main classes: date, time, datetime, timedelta, tzinfo, and timezone. It includes examples of how to create date and time objects, retrieve the current date, and format date strings using the strftime() method. Additionally, it discusses the use of the timedelta class for date manipulations and mentions the pytz module for handling time zones.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Date_&_Time.ipynb - Colaboratory

The document provides an overview of the Python DateTime module, detailing its six main classes: date, time, datetime, timedelta, tzinfo, and timezone. It includes examples of how to create date and time objects, retrieve the current date, and format date strings using the strftime() method. Additionally, it discusses the use of the timedelta class for date manipulations and mentions the pytz module for handling time zones.

Uploaded by

Shreya Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

18/11/2023, 19:10 Date_&_Time.

ipynb - Colaboratory

Python DateTime module


Python Datetime module supplies classes to work with date and time. These classes provide a
number of functions to deal with dates, times, and time intervals. Date and DateTime are an object
in Python, so when you manipulate them, you are actually manipulating objects and not strings or
timestamps.

The DateTime module is categorized into 6 main classes –

1. date – An idealized naive date, assuming the current Gregorian calendar always was, and
always will be, in effect. Its attributes are year, month, and day.
2. time – An idealized time, independent of any particular day, assuming that every day has
exactly 246060 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
3. datetime – Its a combination of date and time along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
4. timedelta – A duration expressing the difference between two date, time, or datetime
instances to microsecond resolution.
5. tzinfo – It provides time zone information objects.
6. timezone – A class that implements the tzinfo abstract base class as a fixed offset from the
UTC (New in version 3.2).

Date class
The date class is used to instantiate date objects in Python. When an object of this class is
instantiated, it represents a date in the format YYYY-MM-DD. The constructor of this class needs
three mandatory arguments year, month, and date.

Python Date class Syntax

class datetime.date(year, month, day)

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 1/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

# Python program to demonstrate date class

# import the date class


from datetime import date

my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)

# Uncommenting my_date = date(1996, 12, 39)


# will raise an ValueError as it is outside range

# uncommenting my_date = date('1996', 12, 11)


# will raise a TypeError as a string is passed instead of integer

Date passed as argument is 1996-12-11

Get the Current Date

To return the current local date today() function of the date class is used. today() function comes
with several attributes (year, month, and day). These can be printed individually.

# Python program to print current date

from datetime import date

# calling the today function of date class


today = date.today()

print("Today's date is", today)

Today's date is 2023-11-18

from datetime import date

# date object of today's date


today = date.today()

print("Current year:", today.year)


print("Current month:", today.month)
print("Current day:", today.day)

Current year: 2023


Current month: 11
Current day: 18

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 2/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

from datetime import datetime

# Getting Datetime from timestamp


date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)

Datetime from timestamp: 2029-10-25 16:17:48

Time class
The time class creates the time object which represents local time, independent of any day.

Constructor Syntax:

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

# Python program to demonstrate time class

from datetime import time

# calling the constructor


my_time = time(13, 24, 56)

print("Entered time", my_time)

# calling constructor with 1 argument


my_time = time(minute=12)
print("\nTime with one argument", my_time)

# Calling constructor with 0 argument


my_time = time()
print("\nTime without argument", my_time)

# Uncommenting time(hour = 26)


# will rase an ValueError as it is out of range

# uncommenting time(hour ='23')


# will raise TypeError as string is passed instead of int

Entered time 13:24:56

Time with one argument 00:12:00

Time without argument 00:00:00

DateTime object representing DateTime in Python


https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 3/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

from datetime import datetime

# Calling now() function


today = datetime.now()

print("Current date and time is", today)

Current date and time is 2023-11-18 10:57:02.725857

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.

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).

import datetime

x = datetime.datetime(2024, 5, 23)

print(x)

2024-05-23 00:00:00

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:

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 4/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 5/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

from datetime import datetime as dt

# Getting current date and time


now = dt.now()
print("Without formatting", now)

# Example 1
s = now.strftime("%A %m %-Y")
print('\nExample 1:', s)

# Example 2
s = now.strftime("%a %-m %y")
print('\nExample 2:', s)

# Example 3
s = now.strftime("%-I %p %S")
print('\nExample 3:', s)

# Example 4
s = now.strftime("%H:%M:%S")
print('\nExample 4:', s)

Without formatting 2023-11-18 11:01:29.390786

Example 1: Saturday 11 2023

Example 2: Sat 11 23

Example 3: 11 AM 29

Example 4: 11:01:29

Python timedelta class is used for calculating differences in dates and also can be used for date
manipulations in Python. It is one of the easiest ways to perform date manipulations.

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 6/7
18/11/2023, 19:10 Date_&_Time.ipynb - Colaboratory

from datetime import datetime, timedelta

# Using current time


ini_time_for_now = datetime.now()

# printing initial_date
print("initial_date", str(ini_time_for_now))

# Calculating future dates for two years


Python Datetime.tzinfo()
future_date_after_2yrs = ini_time_for_now + timedelta(days=730)

The datetime.now() function


future_date_after_2days contains no information
= ini_time_for_now regarding time zones. It only makes use of the
+ timedelta(days=2)

current system time. Tzinfo is an abstract base class in Python. It cannot be directly instantiated. A
# printing calculated future_dates
concrete subclass must derive fromstr(future_date_after_2yrs))
print('future_date_after_2yrs:', this abstract class and implement the methods offered by it.
print('future_date_after_2days:', str(future_date_after_2days))

Python DateTime
initial_date 2023-11-18timezone
11:01:01.952827
future_date_after_2yrs: 2025-11-17 11:01:01.952827
Timezones in DateTime can be used
future_date_after_2days: in the case
2023-11-20 where one might want to display time according to
11:01:01.952827
the timezone of a specific region. This can be done using the pytz module of Python. This module
serves the date-time conversion functionalities and helps users serving international client bases.

from datetime import datetime

https://colab.research.google.com/drive/1usLrMDEMugNDAExYrSvBC8KBOUHkmUUO#printMode=true 7/7

You might also like