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.
Introduction
Primeiro criamos nosso arquivo date-hour.py
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.
Datetime
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)
For example, returning a current date:
2021-01-24 17:04:18.329567
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)
Timedelta
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)
For example, returning a difference of 2 hours:
2:00:00
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 date-hour.py 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
Until the next post <3
Top comments (0)