SlideShare a Scribd company logo
Copyright @ 2015 Learntek. All Rights Reserved. 1
Python modules related to datetime
Copyright @ 2018 Learntek. All Rights Reserved. 3
Python DateTime modules:
In this article, we will see the Python DateTime module. We will learn how to create
current time, how to calculate the time gap and how to produce time difference?
According to Python docs
“The python DateTime module supplies classes for manipulating dates and times in
both simple and complex ways”.
So, python DateTime modules contain several classes. Let us discuss one by one.
Python DateTime Modules — The Datetime.datetime
Let us discuss the useful methods of the DateTime.datetime class.
Copyright @ 2018 Learntek. All Rights Reserved. 4
Python DateTime Modules — The Datetime.datetime
Let us discuss the useful methods of the DateTime.datetime class.
Datetime.datetime.today()
The Datetime.datetime.today() print the today’s date. See the example below.
>>> print datetime.datetime.today()
2018–08–19 22:49:24.169000
datetime.datetime.now()
The datetime.datetime.now() displays the same output as produced by the
datetime.datetime.today().
>>> print datetime.datetime.now()
2018–08–19 22:49:51.541000
Copyright @ 2018 Learntek. All Rights Reserved. 5
But if you provide time zone then the datetime.datetime.now() returns the current
time according to time zone.
>>>
>>> import pytz
>>> pytz.utc
>>> print datetime.datetime.now(pytz.utc)
2018–08–19 17:23:34.614000+00:00
If you provide the time zone information in string then interpreter throws an error.
>>> print datetime.datetime.now(‘US/Eastern’)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: tzinfo argument must be None or of a tzinfo subclass, not type ‘str’
>>>
Copyright @ 2018 Learntek. All Rights Reserved. 6
datetime.strptime(date_string, format)
The datetime.strptime(date_string, format) take date_string and format as argument
and returns the datetime object. As shown below.
>>> import datetime
>>> datetime.datetime.strptime(“May 12 2018”, “%B %d %Y”)
datetime.datetime(2018, 5, 12, 0, 0)
>>> print datetime.datetime.strptime(“May 12 2018 13:03:29”, “%B %d %Y
%H:%M:%S”)
2018–05–12 13:03:29
Strftime(format)
The strftime(format) is used generate the formatted date from datetime object.
>>> print datetime.datetime.now().strftime(“%d %b, %Y”)
22 Aug, 2018
Copyright @ 2018 Learntek. All Rights Reserved. 7
Ctime()
Converts the seconds to a 24-character string of the following form: “Mon Jun 20
23:21:05 1994”.
>>> datetime.datetime.now().ctime()
‘Thu Aug 23 00:07:28 2018’
>>>
isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example
>>> datetime.datetime.now().isoformat()
‘2018–08–23T00:11:32.393000’
>>>
Copyright @ 2018 Learntek. All Rights Reserved. 8
datetime.date
Let us discuss new class datetime.date.
datetime.today()
The method returns today’s date. For example.
>>> import datetime
>>> print datetime.datetime.today()
2018–08–23 23:18:22.044000
>>>
datetime.date.fromtimestamp()
The method converts Unix stamp or epoch to date.
For example
>>> print datetime.date.fromtimestamp(0)
1970–01–01
Copyright @ 2018 Learntek. All Rights Reserved. 9
>>>
>>> import time
>>> time.time()
1535047001.754
>>>
>>> print
datetime.date.fromtimestamp(1535047001.754)
2018–08–23
>>>
Copyright @ 2018 Learntek. All Rights Reserved. 10
datetime.timedelta
The class datetime.timedelta is used to create time difference between two dates
or times.
The class DateTime.timedelta takes keyworded arguments. According to py docs
All arguments are optional and default to 0. Arguments may be ints, longs, or floats,
and may be positive or negative.
Only days, seconds and microseconds are stored internally. Arguments are
converted to those units:
Let us create different-2 exercises for delta.
Copyright @ 2018 Learntek. All Rights Reserved. 11
Let us create time delta of 10 seconds.
>>> import datetime
>>> delta1=datetime.timedelta(seconds=10)
Subtract the time delta to the current time.
>>> now1 = datetime.datetime.now()
>>> now1
datetime.datetime(2018, 8, 24, 22, 53, 56, 488000)
>>> print now1
2018–08–24 22:53:56.488000
>>> print now1 — delta1
2018–08–24 22:53:46.488000
Add the time delta to the current time.
>>> print now1 + delta1
2018–08–24 22:54:06.488000
>>>
Let us do one complete exercise.
1. Create a Unix time means an epoch of 10 days ago.
2. Create a Unix time 10 days later.
Let us do step by step
>>> import datetime
>>> import time
Copyright @ 2018 Learntek. All Rights Reserved.
Create two deltas for time difference one for 10 days ago and one for 10 days later.
>>> delta1=datetime.timedelta(days=10)
>>> delta2=datetime.timedelta(days=-10)
Add both the deltas to the current time.
>>> now1 = datetime.datetime.now()
>>> ten_days_ago = now1+delta2
>>>
>>> ten_days_later = now1+delta1
>>>
>>> print ten_days_ago
2018–08–14 23:09:04.861000
>>>
Copyright @ 2018 Learntek. All Rights Reserved.
>>> print ten_days_later
2018–09–03 23:09:04.861000
>>>
In order to remove floating point use, strftime method has been used.
>>> date1 = ten_days_ago.strftime( “%Y-%m-%d %H:%M:%S” )
>>> date1
‘2018–08–14 23:09:04’
By the use time module, the Unix time or epochs have been created.
>>> int(time.mktime(time.strptime(date1, ‘%Y-%m-%d %H:%M:%S’) ) )
1534268344
>>>
>>> date2 = ten_days_later.strftime(“%Y-%m-%d %H:%M:%S”)
>>>
Copyright @ 2018 Learntek. All Rights Reserved.
Copyright @ 2018 Learntek. All Rights Reserved.
>>>
>>> int(time.mktime( time.strptime(date2, ‘%Y-%m-%d %H:%M:%S’) ) )
1535996344
>>>
Python Calendar module
Now we’ll use calendar module to print the calendar of a particular month. In order to
print a particular month, calendar.month(year, month) would be used as shown below.
>>> import calendar
>>> print calendar.month(2018,8)
August 2018
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
>>>
Let us print the calendar for the 2018 year.
>>> import calendar
>>> print calendar.calendar(2018)
Consider if you want to find out whether a particular year is a leap year or not.
You can use calendar.isleap(year)
See the example below.
>>> calendar.isleap( 2000 )
True
Copyright @ 2018 Learntek. All Rights Reserved.
>>> calendar.isleap( 2001 )
False
>>> calendar.isleap( 2016 )
True
>>> calendar.isleap( 1992 )
Consider you want to find out the number of leap year in the range of y1 to y2.
See the example below.
>>> calendar.leapdays( 1992 , 2016 )
6
>>> calendar.leapdays( 1991 , 2015 )
6
>>>
Copyright @ 2018 Learntek. All Rights Reserved.
Copyright @ 2018 Learntek. All Rights Reserved.
The last year is not included in the range.
Consider you might want to know the time of the different countries.
By default, time-related modules return the time according
to your time zone. Let see how to get the time of the different country
>>> import datetime
>>> import pytz
Let us check the current time of ‘US/Eastern’.
>>> print datetime.datetime.now(pytz.timezone(‘US/Eastern’))
2018–08–25 14:25:34.712000–04:00
>>>
Let us check the current time of India.
Copyright @ 2018 Learntek. All Rights Reserved.
>>> print datetime.datetime.now(pytz.timezone(‘Asia/Kolkata’))
2018–08–25 23:56:40.564000+05:30
If you don’t know the name of the timezone, then you can use search the
timezone using the country name.
>>> pytz.country_timezones.get(“NZ”)
[u’Pacific/Auckland’, u’Pacific/Chatham’]
>>>
New Zealand has two timezones.
Let us check the name of the timezone of India
>>> pytz.country_timezones.get(“IN”)
[u’Asia/Kolkata’]
>>>
pytz.country_timezones.keys()
The above line returns the list of country abbreviations as a shown example below.
[u’BD’, u’BE’, u’BF’, u’BG’, u’BA’, u’BB’, u’WF’, u’BL’, u’BM’, u’BN’, u’BO’, u’BH’, u’BI’, u’BJ’,
u’BT’, u’JM’, u’BW’, u’WS’, u’BQ’, u’BR’, u’BS’, u’JE’, u’BY’ So on…….]
If you want to be confirmed whether ‘abbreviation IN’ belongs to India or other
countries like Iran. You can use Syntax pytz.country_names.get( ‘IN’ )
>>> print (pytz.country_names.get( ‘IN’ ) )
India
if you want to check all the countries and its abbreviations. Use the following piece of
code.
Copyright @ 2018 Learntek. All Rights Reserved.
>>> for each in pytz.country_names.iteritems():
… print each
…
(u’BD’, u’Bangladesh’)
(u’BE’, u’Belgium’)
(u’BF’, u’Burkina Faso’)
(u’BG’, u’Bulgaria’)
So, on.
I hope you have enjoyed the Python datetime Modules Article
Copyright @ 2018 Learntek. All Rights Reserved.
Copyright @ 2018 Learntek. All Rights Reserved. 22
For more Training Information , Contact Us
Email : info@learntek.org
USA : +1734 418 2465
INDIA : +40 4018 1306
+7799713624

More Related Content

What's hot

Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
Piyush rai
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
Sharath Ankrajegowda
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
Python final ppt
Python final pptPython final ppt
Python final ppt
Ripal Ranpara
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
Edureka!
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In Python
Simplilearn
 
Python : Data Types
Python : Data TypesPython : Data Types
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
Priyanka Pradhan
 

What's hot (20)

Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
Data types in python
Data types in pythonData types in python
Data types in python
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
 
Map, Filter and Reduce In Python
Map, Filter and Reduce In PythonMap, Filter and Reduce In Python
Map, Filter and Reduce In Python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 

Similar to Python datetime

Python time
Python timePython time
Python time
Janu Jahnavi
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
jaipur2
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
ankit11134
 
Date object.pptx date and object v
Date object.pptx date and object        vDate object.pptx date and object        v
Date object.pptx date and object v
22x026
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx
BRIJESH KUMAR
 
enum_comp_exercicio01.docx
enum_comp_exercicio01.docxenum_comp_exercicio01.docx
enum_comp_exercicio01.docx
Michel Valentim
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
Fulvio Corno
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
Serhii Kartashov
 
The Future of Sharding
The Future of ShardingThe Future of Sharding
The Future of Sharding
EDB
 
PLC Programming Example - PLC Clock - Answ
PLC Programming Example - PLC Clock - AnswPLC Programming Example - PLC Clock - Answ
PLC Programming Example - PLC Clock - Answ
Business Industrial Network
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeHellen Gakuruh
 
New Java Date/Time API
New Java Date/Time APINew Java Date/Time API
New Java Date/Time API
Juliet Nkwor
 
Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014
Dieter Plaetinck
 
Ruby Time & Date
Ruby Time & DateRuby Time & Date
Ruby Time & Date
Jesus Castello
 
IRJET- Mining Frequent Itemset on Temporal data
IRJET-  	  Mining  Frequent Itemset on Temporal dataIRJET-  	  Mining  Frequent Itemset on Temporal data
IRJET- Mining Frequent Itemset on Temporal data
IRJET Journal
 
Improve data engineering work with Digdag and Presto UDF
Improve data engineering work with Digdag and Presto UDFImprove data engineering work with Digdag and Presto UDF
Improve data engineering work with Digdag and Presto UDF
Kentaro Yoshida
 
Collecting metrics with Graphite and StatsD
Collecting metrics with Graphite and StatsDCollecting metrics with Graphite and StatsD
Collecting metrics with Graphite and StatsD
itnig
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
Java22_1670144363.pptx
Java22_1670144363.pptxJava22_1670144363.pptx
Java22_1670144363.pptx
DilanAlmsa
 

Similar to Python datetime (20)

Python time
Python timePython time
Python time
 
17 ruby date time
17 ruby date time17 ruby date time
17 ruby date time
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
 
Date object.pptx date and object v
Date object.pptx date and object        vDate object.pptx date and object        v
Date object.pptx date and object v
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx
 
enum_comp_exercicio01.docx
enum_comp_exercicio01.docxenum_comp_exercicio01.docx
enum_comp_exercicio01.docx
 
Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8Dates and Times in Java 7 and Java 8
Dates and Times in Java 7 and Java 8
 
JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8JSR 310. New Date API in Java 8
JSR 310. New Date API in Java 8
 
The Future of Sharding
The Future of ShardingThe Future of Sharding
The Future of Sharding
 
PLC Programming Example - PLC Clock - Answ
PLC Programming Example - PLC Clock - AnswPLC Programming Example - PLC Clock - Answ
PLC Programming Example - PLC Clock - Answ
 
SessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTimeSessionSeven_WorkingWithDatesandTime
SessionSeven_WorkingWithDatesandTime
 
New Java Date/Time API
New Java Date/Time APINew Java Date/Time API
New Java Date/Time API
 
Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014
 
Ruby Time & Date
Ruby Time & DateRuby Time & Date
Ruby Time & Date
 
IRJET- Mining Frequent Itemset on Temporal data
IRJET-  	  Mining  Frequent Itemset on Temporal dataIRJET-  	  Mining  Frequent Itemset on Temporal data
IRJET- Mining Frequent Itemset on Temporal data
 
Improve data engineering work with Digdag and Presto UDF
Improve data engineering work with Digdag and Presto UDFImprove data engineering work with Digdag and Presto UDF
Improve data engineering work with Digdag and Presto UDF
 
Collecting metrics with Graphite and StatsD
Collecting metrics with Graphite and StatsDCollecting metrics with Graphite and StatsD
Collecting metrics with Graphite and StatsD
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
 
Java22_1670144363.pptx
Java22_1670144363.pptxJava22_1670144363.pptx
Java22_1670144363.pptx
 

More from sureshraj43

What is maven
What is mavenWhat is maven
What is maven
sureshraj43
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
sureshraj43
 
Ansible: Simple yet powerful IT automation tool
Ansible: Simple yet powerful IT automation toolAnsible: Simple yet powerful IT automation tool
Ansible: Simple yet powerful IT automation tool
sureshraj43
 
Machine learning and pattern recognition
Machine learning and pattern recognitionMachine learning and pattern recognition
Machine learning and pattern recognition
sureshraj43
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
sureshraj43
 
Business analyst tools
Business analyst toolsBusiness analyst tools
Business analyst tools
sureshraj43
 

More from sureshraj43 (6)

What is maven
What is mavenWhat is maven
What is maven
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Ansible: Simple yet powerful IT automation tool
Ansible: Simple yet powerful IT automation toolAnsible: Simple yet powerful IT automation tool
Ansible: Simple yet powerful IT automation tool
 
Machine learning and pattern recognition
Machine learning and pattern recognitionMachine learning and pattern recognition
Machine learning and pattern recognition
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Business analyst tools
Business analyst toolsBusiness analyst tools
Business analyst tools
 

Recently uploaded

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 

Recently uploaded (20)

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 

Python datetime

  • 1. Copyright @ 2015 Learntek. All Rights Reserved. 1
  • 3. Copyright @ 2018 Learntek. All Rights Reserved. 3 Python DateTime modules: In this article, we will see the Python DateTime module. We will learn how to create current time, how to calculate the time gap and how to produce time difference? According to Python docs “The python DateTime module supplies classes for manipulating dates and times in both simple and complex ways”. So, python DateTime modules contain several classes. Let us discuss one by one. Python DateTime Modules — The Datetime.datetime Let us discuss the useful methods of the DateTime.datetime class.
  • 4. Copyright @ 2018 Learntek. All Rights Reserved. 4 Python DateTime Modules — The Datetime.datetime Let us discuss the useful methods of the DateTime.datetime class. Datetime.datetime.today() The Datetime.datetime.today() print the today’s date. See the example below. >>> print datetime.datetime.today() 2018–08–19 22:49:24.169000 datetime.datetime.now() The datetime.datetime.now() displays the same output as produced by the datetime.datetime.today(). >>> print datetime.datetime.now() 2018–08–19 22:49:51.541000
  • 5. Copyright @ 2018 Learntek. All Rights Reserved. 5 But if you provide time zone then the datetime.datetime.now() returns the current time according to time zone. >>> >>> import pytz >>> pytz.utc >>> print datetime.datetime.now(pytz.utc) 2018–08–19 17:23:34.614000+00:00 If you provide the time zone information in string then interpreter throws an error. >>> print datetime.datetime.now(‘US/Eastern’) Traceback (most recent call last): File “<stdin>”, line 1, in <module> TypeError: tzinfo argument must be None or of a tzinfo subclass, not type ‘str’ >>>
  • 6. Copyright @ 2018 Learntek. All Rights Reserved. 6 datetime.strptime(date_string, format) The datetime.strptime(date_string, format) take date_string and format as argument and returns the datetime object. As shown below. >>> import datetime >>> datetime.datetime.strptime(“May 12 2018”, “%B %d %Y”) datetime.datetime(2018, 5, 12, 0, 0) >>> print datetime.datetime.strptime(“May 12 2018 13:03:29”, “%B %d %Y %H:%M:%S”) 2018–05–12 13:03:29 Strftime(format) The strftime(format) is used generate the formatted date from datetime object. >>> print datetime.datetime.now().strftime(“%d %b, %Y”) 22 Aug, 2018
  • 7. Copyright @ 2018 Learntek. All Rights Reserved. 7 Ctime() Converts the seconds to a 24-character string of the following form: “Mon Jun 20 23:21:05 1994”. >>> datetime.datetime.now().ctime() ‘Thu Aug 23 00:07:28 2018’ >>> isoformat() Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example >>> datetime.datetime.now().isoformat() ‘2018–08–23T00:11:32.393000’ >>>
  • 8. Copyright @ 2018 Learntek. All Rights Reserved. 8 datetime.date Let us discuss new class datetime.date. datetime.today() The method returns today’s date. For example. >>> import datetime >>> print datetime.datetime.today() 2018–08–23 23:18:22.044000 >>> datetime.date.fromtimestamp() The method converts Unix stamp or epoch to date. For example >>> print datetime.date.fromtimestamp(0) 1970–01–01
  • 9. Copyright @ 2018 Learntek. All Rights Reserved. 9 >>> >>> import time >>> time.time() 1535047001.754 >>> >>> print datetime.date.fromtimestamp(1535047001.754) 2018–08–23 >>>
  • 10. Copyright @ 2018 Learntek. All Rights Reserved. 10 datetime.timedelta The class datetime.timedelta is used to create time difference between two dates or times. The class DateTime.timedelta takes keyworded arguments. According to py docs All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. Only days, seconds and microseconds are stored internally. Arguments are converted to those units: Let us create different-2 exercises for delta.
  • 11. Copyright @ 2018 Learntek. All Rights Reserved. 11 Let us create time delta of 10 seconds. >>> import datetime >>> delta1=datetime.timedelta(seconds=10) Subtract the time delta to the current time. >>> now1 = datetime.datetime.now() >>> now1 datetime.datetime(2018, 8, 24, 22, 53, 56, 488000) >>> print now1 2018–08–24 22:53:56.488000
  • 12. >>> print now1 — delta1 2018–08–24 22:53:46.488000 Add the time delta to the current time. >>> print now1 + delta1 2018–08–24 22:54:06.488000 >>> Let us do one complete exercise. 1. Create a Unix time means an epoch of 10 days ago. 2. Create a Unix time 10 days later. Let us do step by step >>> import datetime >>> import time Copyright @ 2018 Learntek. All Rights Reserved.
  • 13. Create two deltas for time difference one for 10 days ago and one for 10 days later. >>> delta1=datetime.timedelta(days=10) >>> delta2=datetime.timedelta(days=-10) Add both the deltas to the current time. >>> now1 = datetime.datetime.now() >>> ten_days_ago = now1+delta2 >>> >>> ten_days_later = now1+delta1 >>> >>> print ten_days_ago 2018–08–14 23:09:04.861000 >>> Copyright @ 2018 Learntek. All Rights Reserved.
  • 14. >>> print ten_days_later 2018–09–03 23:09:04.861000 >>> In order to remove floating point use, strftime method has been used. >>> date1 = ten_days_ago.strftime( “%Y-%m-%d %H:%M:%S” ) >>> date1 ‘2018–08–14 23:09:04’ By the use time module, the Unix time or epochs have been created. >>> int(time.mktime(time.strptime(date1, ‘%Y-%m-%d %H:%M:%S’) ) ) 1534268344 >>> >>> date2 = ten_days_later.strftime(“%Y-%m-%d %H:%M:%S”) >>> Copyright @ 2018 Learntek. All Rights Reserved.
  • 15. Copyright @ 2018 Learntek. All Rights Reserved. >>> >>> int(time.mktime( time.strptime(date2, ‘%Y-%m-%d %H:%M:%S’) ) ) 1535996344 >>> Python Calendar module Now we’ll use calendar module to print the calendar of a particular month. In order to print a particular month, calendar.month(year, month) would be used as shown below. >>> import calendar >>> print calendar.month(2018,8) August 2018 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12
  • 16. 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 >>> Let us print the calendar for the 2018 year. >>> import calendar >>> print calendar.calendar(2018) Consider if you want to find out whether a particular year is a leap year or not. You can use calendar.isleap(year) See the example below. >>> calendar.isleap( 2000 ) True Copyright @ 2018 Learntek. All Rights Reserved.
  • 17. >>> calendar.isleap( 2001 ) False >>> calendar.isleap( 2016 ) True >>> calendar.isleap( 1992 ) Consider you want to find out the number of leap year in the range of y1 to y2. See the example below. >>> calendar.leapdays( 1992 , 2016 ) 6 >>> calendar.leapdays( 1991 , 2015 ) 6 >>> Copyright @ 2018 Learntek. All Rights Reserved.
  • 18. Copyright @ 2018 Learntek. All Rights Reserved. The last year is not included in the range. Consider you might want to know the time of the different countries. By default, time-related modules return the time according to your time zone. Let see how to get the time of the different country >>> import datetime >>> import pytz Let us check the current time of ‘US/Eastern’. >>> print datetime.datetime.now(pytz.timezone(‘US/Eastern’)) 2018–08–25 14:25:34.712000–04:00 >>> Let us check the current time of India.
  • 19. Copyright @ 2018 Learntek. All Rights Reserved. >>> print datetime.datetime.now(pytz.timezone(‘Asia/Kolkata’)) 2018–08–25 23:56:40.564000+05:30 If you don’t know the name of the timezone, then you can use search the timezone using the country name. >>> pytz.country_timezones.get(“NZ”) [u’Pacific/Auckland’, u’Pacific/Chatham’] >>> New Zealand has two timezones. Let us check the name of the timezone of India
  • 20. >>> pytz.country_timezones.get(“IN”) [u’Asia/Kolkata’] >>> pytz.country_timezones.keys() The above line returns the list of country abbreviations as a shown example below. [u’BD’, u’BE’, u’BF’, u’BG’, u’BA’, u’BB’, u’WF’, u’BL’, u’BM’, u’BN’, u’BO’, u’BH’, u’BI’, u’BJ’, u’BT’, u’JM’, u’BW’, u’WS’, u’BQ’, u’BR’, u’BS’, u’JE’, u’BY’ So on…….] If you want to be confirmed whether ‘abbreviation IN’ belongs to India or other countries like Iran. You can use Syntax pytz.country_names.get( ‘IN’ ) >>> print (pytz.country_names.get( ‘IN’ ) ) India if you want to check all the countries and its abbreviations. Use the following piece of code. Copyright @ 2018 Learntek. All Rights Reserved.
  • 21. >>> for each in pytz.country_names.iteritems(): … print each … (u’BD’, u’Bangladesh’) (u’BE’, u’Belgium’) (u’BF’, u’Burkina Faso’) (u’BG’, u’Bulgaria’) So, on. I hope you have enjoyed the Python datetime Modules Article Copyright @ 2018 Learntek. All Rights Reserved.
  • 22. Copyright @ 2018 Learntek. All Rights Reserved. 22 For more Training Information , Contact Us Email : info@learntek.org USA : +1734 418 2465 INDIA : +40 4018 1306 +7799713624