datetime in Python – Simplified Guide with Clear Examples

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.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. How to format the datetime object into any date format?
  6. Useful datetime functions
  7. When and how to use the datetime.time() class?
  8. When and how to use the datetime.timedelta() class?
  9. Timezones
  10. 14 Practice Exercises with Solutions

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.

PyInteractive Python
import datetime

  

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 class
  • time class
  • timedelta 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.

PyInteractive Python
datetime.datetime.now() #> datetime.datetime(2019, 2, 15, 18, 54, 58, 291224)

  

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.

PyInteractive Python
datetime.date.today() #> datetime.date(2019, 2, 15)

  

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.

PyInteractive Python
print(datetime.date.today()) #> 2019-02-15

  

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)

PyInteractive Python
datetime.datetime(2001, 1, 31, 10, 51, 0) #> datetime.datetime(2001, 1, 31, 10, 51)

  

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’

PyInteractive Python
mydatetime = datetime.datetime.fromtimestamp(528756281) mydatetime #> datetime.datetime(1986, 10, 4, 2, 14, 41)

  

You can convert the datetime back to a unixtimestamp as follows:

PyInteractive Python
mydatetime.timestamp() #> 528756281.0

  

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.

from dateutil.parser import parse
parse('January 31, 2010')
#> datetime.datetime(2010, 1, 31, 0, 0)

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:

from dateutil.parser import parse
parse('31, March 31, 2010, 10:51pm')

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.

PyInteractive Python
dt = datetime.datetime(2001, 1, 31, 10, 51, 0) print(dt.strftime('%Y-%m-%d::%H-%M')) #> 2001-01-31::10-51

  

7. Example 2 – Formatting a datetime object

Parse the following datetime object to the following representation: ’31 January, 2001, Wednesday’

PyInteractive Python
# Input dt = datetime.datetime(2001, 1, 31)

  
Show Solution

Solution:

PyInteractive Python
dt.strftime('%d %B, %Y, %A')

  

8. Useful datetime functions

The datetime object contains a number of useful date-time related methods.

PyInteractive Python
# create a datatime obj dt = datetime.datetime(2019, 2, 15) # 1. Get the current day of the month dt.day #> 31 # 2. Get the current day of the week dt.isoweekday() #> 5 --> Friday # 3. Get the current month of the year dt.month #> 2 --> February # 4. Get the Year dt.year #> 2019

  

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.

PyInteractive Python
# hours, minutues, seconds, microseconds tm = datetime.time(10,40,10,102301) tm #> datetime.time(10, 40, 10, 102301)

  

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.

PyInteractive Python
td = datetime.timedelta(days=30) td

  

Now I have a timedelta object that represents a duration of 30 days. Let’s compute the date will be 30 days from now.

PyInteractive Python
print(datetime.date.today() + td) #> 2019-03-17

  

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

PyInteractive Python
td = datetime.timedelta(weeks=1, days=30, hours=2, minutes=40) td #> datetime.timedelta(days=37, seconds=9600)

  

If you subtract two datetime objects you will get a timedelta object that represent the duration.

PyInteractive Python
dt1 = datetime.datetime(2002, 1, 31, 10, 10, 0) dt2 = datetime.datetime(2001, 1, 31, 10, 10, 0) dt1 - dt2 #> datetime.timedelta(days=365)

  

Likewise, you can subtract two time deltas to get another timedelta object.

PyInteractive Python
td1 = datetime.timedelta(days=30) # 30 days td2 = datetime.timedelta(weeks=1) # 1 week td1 - td2 #> datetime.timedelta(days=23)

  

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.

import pytz
datetime.datetime(2001, 1, 31, 10, 10, 0, tzinfo=pytz.UTC)

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.

# See available time zones
pytz.all_timezones[:5]
#> ['Africa/Abidjan',
#>  'Africa/Accra',
#>  'Africa/Addis_Ababa',
#>  'Africa/Algiers',
#>  'Africa/Asmara']
# Set to particular timezone
dt_in = datetime.datetime(2001, 1, 31, 3, 30, 0, 0, tzinfo=pytz.timezone('Asia/Tokyo'))
dt_in
#> datetime.datetime(2001, 1, 31, 3, 30, tzinfo=<DstTzInfo 'Asia/Tokyo' LMT+9:19:00 STD>)

You can know that by converting to respective target timezone.

tgt_timezone = pytz.timezone('Africa/Addis_Ababa')
dt_in.astimezone(tgt_timezone)

12. Practice Examples

Rules for the challenges:

  1. No looking at the calendar
  2. 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)

PyInteractive Python
# Input s1 = "2010 Jan 1" s2 = '31-1-2000' s3 = 'October10, 1996, 10:40pm' # Deisred Output #> 2010-01-01 00:00:00 #> 2000-01-31 00:00:00 #> 2019-10-10 22:40:00

  
Show Solution
# Input
s1 = "2010 Jan 1"
s2 = '31-1-2000'
s3 = 'October10,1996, 10:40pm'

# Solution
from dateutil.parser import parse
print(parse(s1))
print(parse(s2))
print(parse(s3))
#> 2010-01-01 00:00:00
#> 2000-01-31 00:00:00
#> 2019-10-10 22:40:00

Exercise 2: How many days has it been since you were born?

How many days has it been since you were born? (easy)

PyInteractive Python
# Input bday = 'Oct 2, 1869' # use bday

  
Show Solution
# Input
bday = 'Oct 2, 1869'

import datetime
from dateutil.parser import parse

# Solution
td = datetime.datetime.now() - parse(bday)
td.days
#> 54558

Exercise 3: How to count the number of saturdays between two dates?

Count the number of saturdays between two dates (medium)

PyInteractive Python
# Input import datetime d1 = datetime.date(1869, 1, 2) d2 = datetime.date(1869, 10, 2) # Desired Output #> 40

  
Show Solution
PyInteractive Python
# Input import datetime d1 = datetime.date(1869, 1, 2) d2 = datetime.date(1869, 10, 2) # Solution delta = d2 - d1 # timedelta # Get all dates dates_btw_d1d2 = [(d1 + datetime.timedelta(i)) for i in range(delta.days + 1)] n_saturdays = 0 for d in dates_btw_d1d2: n_saturdays += int(d.isoweekday() == 6) print(n_saturdays) #> 40

  

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)

PyInteractive Python
# Input bday = 'Oct 2, 1869' # use b'day

  
Show Solution
# Input
bday = 'Oct 2, 1869'  # Enter birthday here

import datetime
from dateutil.parser import parse

# Solution
bdate = parse(bday)
current_bdate = datetime.date(year=datetime.date.today().year, month=bdate.month, day=bdate.day)
td = current_bdate - datetime.date.today()
td.days
#> 228

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)

PyInteractive Python
# Input ['Oct, 2, 1869', 'Oct, 10, 1869', 'Oct, 15, 1869', 'Oct, 20, 1869', 'Oct, 23, 1869'] # Desired Output #> [8, 5, 5, 3]

  
Show Solution
# Input
datestrings = ['Oct, 2, 1869', 'Oct, 10, 1869', 'Oct, 15, 1869', 'Oct, 20, 1869', 'Oct, 23, 1869']

# Solution
import datetime
from dateutil.parser import parse
import numpy as np

dates = [parse(d) for d in datestrings]

print([d.days for d in np.diff(dates)])
#> [8, 5, 5, 3]

Exercise 6: How to convert number of days to seconds?

Convert the number of days till your next birthday to seconds (easy)

PyInteractive Python
# Input import datetime bdate = datetime.date(1869, 10, 2) td = datetime.date.today() - bdate

  
Show Solution
PyInteractive Python
# Input import datetime bdate = datetime.date(1869, 10, 2) td = datetime.date.today() - bdate # Solution td.total_seconds() #> 4713811200.0

  

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)

PyInteractive Python
# Input import datetime date = datetime.date(1869, 10, 2) # Desired Output #> 1869-10-02 00:00:00

  
Show Solution
PyInteractive Python
from datetime import date, datetime d = date(1869, 10, 2) print(datetime.combine(d, datetime.min.time())) #> 1869-10-02 00:00:00 #> 1869-10-02 00:00:00

  

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)

PyInteractive Python
# Input import datetime dt = datetime.date(1952, 2, 12) # Desired Output #> 29

  
Show Solution
PyInteractive Python
# Input import datetime dt = datetime.date(1952, 2, 12) # Solution import calendar calendar.monthrange(dt.year,dt.month)[1] #> 29

  

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
PyInteractive Python
import datetime from calendar import monthrange d1 = datetime.date(1948, 2, 1) n_days = monthrange(1948, 2) # Get all dates dates_btw_d1d2 = [(d1 + datetime.timedelta(i)) for i in range(n_days[1])] n_sundays = 0 for d in dates_btw_d1d2: n_sundays += int(d.isoweekday() == 6) print(n_sundays) #> 4 #> 4

  

Exercise 10: How to format a given date to “mmm-dd, YYYY” fortmat?

Format a given date to “mmm-dd, YYYY” fortmat? (easy)

# input
import datetime
d1 = datetime.date('2010-09-28')

# Desired output
#> 'Sep-28, 2010'
Show Solution
PyInteractive Python
# Input import datetime d1 = datetime.date(2010, 9, 28) # Solution d1.strftime('%b-%d, %Y') #> 'Sep-28, 2010'

  

Exercise 11: How to convert datetime to Year-Qtr format?

Convert the below datetime to Year-Qtr format? (easy)

PyInteractive Python
# input import datetime d1 = datetime.datetime(2010, 9, 28, 10, 40, 59) # Desired output #> '2010-Q3'

  
Show Solution
PyInteractive Python
# input import datetime d1 = datetime.datetime(2010, 9, 28, 10, 40, 59) # Solution f'{d1.year}-Q{d1.month//4 + 1}' #> '2010-Q3'

  

Exercise 12: How to convert unix timestamp to a readable date?

Convert the below unix timestamp to a readable date (medium)

PyInteractive Python
# Input unixtimestamp = 528756281 # Desired Output #> 04-October-1986

  
Show Solution
PyInteractive Python
# Input unixtimestamp = 528756281 # Solution import datetime dt = datetime.datetime.fromtimestamp(528756281) dt.strftime('%d-%B-%Y') #> '04-October-1986'

  

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)

import datetime
dt_in = datetime.datetime(2001, 1, 31, 3, 30, 0, 0, tzinfo=pytz.timezone('Asia/Tokyo'))

# Desired Solution
#> datetime.datetime(2001, 1, 30, 23, 41, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
Show Solution
import datetime
dt_in = datetime.datetime(2001, 1, 31, 3, 30, 0, 0, tzinfo=pytz.timezone('Asia/Tokyo'))

# Solution
india_tz = pytz.timezone('Asia/Kolkata')
dt_in.astimezone(india_tz)
datetime.datetime(2001, 1, 30, 23, 41, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)

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)

PyInteractive Python
# Input ['Oct 2, 1869', 'Oct 5, 1869', 'Oct 7, 1869', 'Oct 9, 1869'] # Desired Output #> ['Oct 02, 1869', 'Oct 03, 1869', 'Oct 04, 1869', 'Oct 05, 1869', #> 'Oct 06, 1869', 'Oct 07, 1869', 'Oct 08, 1869', 'Oct 09, 1869']

  
Show Solution
# Input
datestrings = ['Oct 2, 1869', 'Oct 5, 1869', 'Oct 7, 1869', 'Oct 9, 1869']

# Solution
import datetime
from dateutil.parser import parse
import numpy as np

dates = [parse(d) for d in datestrings]

d1 = np.min(dates)
d2 = np.max(dates)

delta = d2 - d1  # timedelta

# Get all dates
dates_btw_d1d2 = [(d1 + datetime.timedelta(i)).strftime('%b %d, %Y') for i in range(delta.days + 1)]
print(dates_btw_d1d2)
#> ['Oct 02, 1869', 'Oct 03, 1869', 'Oct 04, 1869', 'Oct 05, 1869', 'Oct 06, 1869', 'Oct 07, 1869', 'Oct 08, 1869', 'Oct 09, 1869']

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!