DEV Community 👩‍💻👨‍💻

Cover image for Working with Date and Time in Python
Guilherme Haynes Howe
Guilherme Haynes Howe

Posted on

Working with Date and Time in Python

Say dev, how are you?

In the last week, I took a job where I needed to calculate days and hours with Python. With some Google searches I came up with several results, some really good and others like "WTF .-.".

I soon thought to myself, and I said, "I will research how Python works with hours and develop its own algorithm for that", with some research in the python documentation I found that it is easier than I imagined to be working with date and time.


Primeiro criamos nosso arquivo
In python we have the datetime module that provides various date and time manipulation objects, such as date, time, datetime, timedelta, tzinfo and timezone. In this post we will talk about datetime and timedelta.


Combining all the date and time attributes, it returns a tuple like the one below:

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
Enter fullscreen mode Exit fullscreen mode

For example, returning a current date:

2021-01-24 17:04:18.329567
Enter fullscreen mode Exit fullscreen mode

Its default format is:

  • Year: 4 Digits
  • Month: 2 Digits
  • Day: 2 Digits
  • Hour: 2 Digits
  • Minute: 2 Digits
  • Seconds: 2 Digits + 6 Digits (to differentiate microseconds)


Represents the duration or the difference between two dates or times. It can be represented as follows:

timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Enter fullscreen mode Exit fullscreen mode

For example, returning a difference of 2 hours:

Enter fullscreen mode Exit fullscreen mode

Putting hands in the dough

After presenting the objects we are going to work on, we will start to do some tests. I will comment line by line on what is happening, and in the end, post the result of everything.

First we create our file:

  • Line 1: I import datetime and timedelta from the datetime module
  • Line 3: I take the current datetime, saving it in the variable now
  • Line 5: Black the tuple generated on the screen
  • Line 7: I generated a 2-hour timedelta and saved it in the td variable
  • Line 10: I entered the current time
  • Line 11: I printed the sum of the current time and the timedelta
  • Line 12: I subtracted the current time with the timedelta

Output of the above commands:

Datetime tuple: 2021-01-24 17:39:28.446383
Timedelta: 2:00:00

Current Time 2021-01-24 17:39:28.446383
+2 hours 2021-01-24 19:39:28.446383
-2 hours 2021-01-24 15:39:28.446383
Enter fullscreen mode Exit fullscreen mode

Until the next post <3

Top comments (0)

CLI tools you won't be able to live without 🔧

CLI tools