How to calculate "xx time" in one shot with Python timedelta

Introduction

Now I work almost fully remotely, eliminating the need to spend time commuting. It's great because I can use that time elsewhere, but I'm worried that I'll have less opportunity to move and I can't have time to listen to the podcast. To solve both of them, I started to walk to a supermarket (opening at 8 am!) A little away every morning, but I heard today a podcast called PythonBytes I've been talking about crazy tips from my eyes, so I'll introduce them.

The people talking on the podcast also said, "Well, can you do that?" "I didn't know," but I was surprised to hear that. For those who want to hear directly, 27 of Episode # 190 It's about a minute.

What is timedelta

timedelta is a feature included in the python standard library and is included in the datetime module. When the datetimes are subtracted from each other, timedelta type data is returned.

Call datetime.now () twice to get the current time and try to get the difference.

>>> from datetime import datetime, timedelta
>>> d0 = datetime.now()
>>> d1 = datetime.now()
>>> td = d1 - d0
>>> td
datetime.timedelta(seconds=1, microseconds=508102)

The result of the difference is data of type timedelta, in which case the difference between the two times is 1 second + 508102 microseconds = 1.508102 seconds. Each value can be obtained as an attribute value.

>>> td.days
0
>>> td.seconds
1
>>> td.microseconds
508102

Now consider a slightly larger difference.

>>> d0 = datetime(2020,7,31,22,5,0, 113459)
>>> d1 = datetime(2020,8,3,5,55,26, 93450)
>>> d1 - d0
datetime.timedelta(days=2, seconds=28225, microseconds=979991)

From 22:05: 0.113459 on July 31st to 5:55: 26.093450 on August 3rd. Just subtract the two date times and you'll see that the difference is 2 days and 28225.979991 seconds. In this example, the difference between the dates across the months is taken, and if you do it by hand, it will be troublesome and easy to make a mistake, but it is very helpful that datetime is doing it.

Convert timedelta to time

Although it can be calculated easily like this, "2 days and 28225.979991 seconds" is subtly difficult to understand. How many hours is this? The hurdle goes up as soon as I think. The first thing that comes to mind is to take out the attribute value and calculate it.

>>> td.days * 24 + (td.seconds + td.microseconds / 1000000 ) / 60 / 60
55.8405499975

Or you can use the total_seconds () method to make it a little easier.

>>> td.total_seconds() / 60 / 60
55.840549997500005

There is a slight error here.

In any case, it's not a difficult calculation, but it's a shame that I can't use it even though I have a special type called timedelta.

But actually, I can. That is the main subject of today, but the solution is very simple: "** Divide by the unit timedelta you want to calculate **".

For example, in the above case

>>> td / timedelta (hours=1)
55.8405499975

Oh, isn't it amazing? I will write a little about why this happens.

Although timedelta has three attribute values, days, seconds, and microseconds, the constructor also supports other time units with keyword arguments.

>>> timedelta(minutes=1)
datetime.timedelta(seconds=60)
>>> timedelta(hours=1)
datetime.timedelta(seconds=3600)
>>> timedelta(weeks=1)
datetime.timedelta(days=7)

As you can see, if specified in a different unit, it will be normalized to days, seconds, microseconds and saved as an attribute of timedelta.

And the division between timedeltas will calculate the ratio of the two time intervals, and the result will be a float (floating point type). Therefore, if it is in "hours", you can get the desired value by dividing by timedelta (hours = 1).

By applying this, for example, when you think "How many weeks is 5/6 to 8/19?"

>>> (datetime (2020, 8,19) - datetime (2020, 5, 6)) / timedelta(weeks=1)
15.0

Can be calculated in one shot.

Summary

It's been a long time since datetime was introduced in Python, but I've never used timedelta like this before. According to the podcast, this isn't a trick, it seems to be the usage intended by the author of timedelta himself, but if that's the case, I'd like you to make an example in the document or make an effort to spread it a little more ( Lol)

Recommended Posts

How to calculate "xx time" in one shot with Python timedelta
How to convert 0.5 to 1056964608 in one shot
How to calculate date with python
How to work with BigQuery in Python
[REAPER] How to play with Reascript in Python
How to measure execution time with Python Part 1
How to use tkinter with python in pyenv
How to measure execution time with Python Part 2
How to get the date and time difference in seconds with python
How to convert / restore a string with [] in python
How to do hash calculation with salt in Python
How to measure processing time in Python or Java
Explain in detail how to make sounds with python
How to do zero-padding in one line with OpenCV
How to run tests in bulk with Python unittest
How to measure mp3 file playback time with python
How to develop in Python
How to embed multiple embeds in one message with Discord.py
How to adapt multiple machine learning libraries in one shot
How to check ORM behavior in one file with django
[Python] How to write an if statement in one sentence.
How to generate exponential pulse time series data in python
[Python] Plotly draws Pandas dataframes in one shot with Cufflinks
How to log in to AtCoder with Python and submit automatically
[Python] How to do PCA in Python
Python: How to use async with
How to collect images in Python
How to use SQLite in Python
Try to calculate Trace in Python
How to get started with Python
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use FTP with Python
How to use PubChem in Python
How to handle Japanese in Python
How to deal with python installation error in pyenv (BUILD FAILED)
How to not escape Japanese when dealing with json in python
How to create a heatmap with an arbitrary domain in Python
How to use python put in pyenv on macOS with PyCall
How to write offline real time Solve E04 problems in Python
How to write offline real time Solve F01 problems with Python
[Introduction to Python] How to use class in Python?
Try logging in to qiita with Python
How to access environment variables in Python
How to dynamically define variables in Python
How to do R chartr () in Python
[Itertools.permutations] How to put permutations in Python
How to display multiplication table in python
How to extract polygon area in Python
How to do portmanteau test with python
How to check opencv version in python
How to display python Japanese with lolipop
One liner webServer (with CGI) in python
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to enter Japanese with Python curses
[Python] How to calculate MAE and RMSE
To work with timestamp stations in Python