datetime in Python
datetime in Python – Simplified Guide with Clear Examples
by Selva Prabhakaran | Posted on April 13, 2019
datetime
is the standard module for working with dates in python. It provides 4 main objects for date and time operations: datetime
, date
, time
and timedelta
. In this post you will learn how to do all sorts of operations with these objects and solve date-time related practice problems (easy to hard) in Python.datetime in Python – Simplified Guide with Clear Examples. Photo by Sergio.
Content
1. Introduction to datetime 2. How to get the current date and the time in Python 3. How to create the datetime object 4. How to parse a string to datetime in python? 5. Example 1 – Parsing a date string to datetime 6. How to format the datetime object into any date format? 7. Example 2 – Formatting a datetime object 8. Useful datetime functions 9. When and how to use the datetime.time() class? 10. When and how to use the datetime.timedelta() class? 11. How to work with timezones?
1. Introduction to datetime
The datetime
is the main module for working with dates in python. Whenever you need to work with dates in python, datetime
module provides the necessary tools.
datetime
is part of python’s standard library, which means, you don’t need to install it separately.
You can simply import as is.
If you have to learn only one thing about handling dates in datetime
module, it is the datetime.datetime()
class.
Inside datetime
module, the most important and the commonly used object is the datetime
class. Notice, I am talking about the datetime
class inside the datetime
module.
Since both the module and the class have the same name, pay attention to what object you are using.
Alright, besides the datetime.datetime
class, there is also the:
date
classtime
classtimedelta
class
Each these classes have its own purpose.
We’ll cover all of these in this post and about a more advanced parser (not in `datetime`) to help parse any date.
2. How to get the current date and the time in Python
The datetime.datetime.now()
method gives the current datetime.
The output is a nice datetime.datetime
object with the current date and time in local time zone. The output is in the following order: ‘year’, ‘month’, ‘date’, ‘hour’, ‘minute’, ‘seconds’, ‘microseconds’.
To get the date alone, use the datetime.date.today()
instead.
It returns a datetime.date
object and not datetime.datetime
. Why? That’s because, today()
is a method of the datetime.date
class and does not contain time information.
Good.
But the above notation hard to read. Printing it out will show in a nice YYYY-mm-dd
format.
We will see how to format datetime to many more formats shortly.
3. How to create the datetime object
We saw how to create the datetime
object for current time. But how to create one for any given date and time? Say, for the following time: 2001-01-31::10:51:00
You can pass it in the same order to datetime.datetime()
. (I will show an easier method in next section)
You can also create a datetime
from a unixtimestamp. A unixtimestamp is nothing but the number of seconds since the epoch date: ‘Jan 01, 1970’
You can convert the datetime
back to a unixtimestamp as follows:
4. How to parse a string to datetime in python?
The above method requires you to manually key in the year, month etc to create a datetime object. But, it not convenient when working with datasets or spreadsheet columns containing date strings.
We need way to automatically parse a given date string, in whatever format, to a datetime object.
Why is this needed?
Because, datasets containing dates are often imported as strings. Secondly, the date can be in any arbitrary date string format, like, ‘2010 Jan 31’ or ‘January 31, 2010′ or even ’31-01-2010’.
So, How to convert a date string to a datetime
?
The parser
module from dateutil
let’s you parse pretty much any date string to a datetime
object.
5. Example 1 – Parsing a date string to datetime
Parse the following date string to a datetime
object: ’31, March 31, 2010, 10:51pm’
Solution:
You can convert any datetime object to nearly any representation of date format using its strftime()
method.
6. How to format the datetime object into any date format?
You can convert any datetime object to nearly any representation of date format using its strftime()
method. You need to pass the right symbol representaion of the date format as an argument.
7. Example 2 – Formatting a datetime object
Parse the following datetime object to the following representation: ’31 January, 2001, Wednesday’
Show Solution
Solution:
8. Useful datetime functions
The datetime object contains a number of useful date-time related methods.
9. When and how to use the datetime.time() class?
The datetime.time()
is used to represnt the time component alone, without the date. The defualt output format is: hours, minutes, seconds and microseconds.
10. When and how to use the datetime.timedelta() class?
‘TimeDeltas’ represent a period of time that a particular time instance. You can think of them simply as the difference between two dates or times.
It is normally used to add or remove a certain duration of time from datetime
objects.
To create a datetime.timedelta
class you need to pass a specified duration to the class constructor. The arguments can be in weeks
,days
(default), hours
, minutes
, seconds
, microseconds
.
Now I have a `timedelta` object that represents a duration of 30 days. Let’s compute the date will be 30 days from now.
Likewise, you can subtract timedeltas as well.
Another convenience with timedeltas is you can create arbitrary combination of time durations represented with days, weeks, hours etc. It will simplify that combination
If you subtract two datetime objects you will get a timedelta object that represent the duration.
Likewise, you can subtract two time deltas to get another timedelta object.
11. How to work with timezones?
For time zones, python recommends pytz
module which is not a standard built-in library. You need to install it separately (enter `pip install pytz` in terminal or command prompt)
So how to set time zone to a particular datetime
?
Simply pass the respective pytz timezone
object to tzinfo
parameter when you create the datetime. Then, that datetime
will become timezone aware. Let’s create a datetime object that belongs to UTC timezone.
UTC was a direct attribute of the pytz
module. So, how to set to a different timezone?
Lookup pytz.all_timezones
for your timezone of choice. Then use the pytz.timezone()
to create the respective timezone object that will be passed to the tzinfo
argument.
You can know that by converting to respective target timezone.
12. Practice Examples
Rules for the challenges:
No looking at the calendar
Solve the problems with python code even if it is possible to compute it mentally
Exercise 1: How to parse date strings to datetime format?
Parse the following date strings to datetime format (easy)
Show Solution
Exercise 2: How many days has it been since you were born?
How many days has it been since you were born? (easy)
Show Solution
Exercise 3: How to count the number of saturdays between two dates?
Count the number of saturdays between two dates (medium)
Show Solution
Exercise 4: How many days is it until your next birthday this year?
How many days is it until your next birthday this year? (easy)
Show Solution
Exercise 5: How to count the number of days between successive days in an irregular sequence?
Count the number of days between successive days in the following list. (medium)
Show Solution
Exercise 6: How to convert number of days to seconds?
Convert the number of days till your next birthday to seconds (easy)
Show Solution
Exercise 7: How to convert a given date to a datetime set at the beginning of the day?
Convert a given date to a datetime set at the beginning of the day (easy)
Show Solution
Exercise 8: How to get the last day of the month for any given date in python?
Get the last day of the month for the below given date in python (easy)
Show Solution
Exercise 9: How many Sundays does the month of February 1948 have?
Count the Sundays does the month of February 1948 have? (medium)Show Solution
Exercise 10: How to format a given date to “mmm-dd, YYYY” fortmat?
Format a given date to “mmm-dd, YYYY” fortmat? (easy)
Show Solution
Exercise 11: How to convert datetime to Year-Qtr format?
Convert the below datetime to Year-Qtr format? (easy)
Show Solution
Exercise 12: How to convert unix timestamp to a readable date?
Convert the below unix timestamp to a readable date (medium)
Show Solution
Exercise 13: How to get the time in a different timezone?
If it is ‘2001-01-31::3:30:0’ in ‘Asia/Tokyo’. What time is it in ‘Asia/Kolkata’? (medium)
Show Solution
Exercise 14: How to fill up missing dates in a given irregular sequence of dates?
Fill up missing dates in a given irregular sequence of dates? (hard)
Show Solution
10. Conclusion
How many were you able to solve? Congratulations if you were able to solve 7 or more.
We covered nearly everything you will need to work with dates in python. Let me know if I have missed anything. Or if you have better answers or have more questions, please write in the comments area below. See you in the next one!
Reference : https://www.machinelearningplus.com/python/datetime-python-examples/
Last updated