# How to use Python to calculate time

I want to write python script that acts as a time calculator.

For example:

Suppose the time is now 13:05:00

I want to add 1 hour, 23 minutes, and 10 seconds to it.

and I want to print the answer out.

How do I do this in Python?

What if date is also involved?

Asked by:

**Dainton457**| Posted: 06-12-2021

# Answer 1

`datetime.timedelta`

is designed for fixed time differences (e.g. 1 day is fixed, 1 month is not).

```
>>> import datetime
>>> t = datetime.time(13, 5)
>>> print t
13:05:00
>>> now = datetime.datetime.now()
>>> print now
2009-11-17 13:03:02.227375
>>> print now + datetime.timedelta(hours=1, minutes=23, seconds=10)
2009-11-17 14:26:12.227375
```

Note that it doesn't make sense to do addition on just a time (but you can combine a date and a time into a datetime object, use that, and then get the time). DST is the major culprit. For example, 12:01am + 5 hours could be 4:01am, 5:01am, or 6:01am on different days.

Answered by:**Samantha511**| Posted: 07-01-2022

# Answer 2

For calculating dates and times there are several options but I will write the simple way:

```
import datetime
import dateutil.relativedelta
# current time
date_and_time = datetime.datetime.now()
date_only = date.today()
time_only = datetime.datetime.now().time()
# calculate date and time
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)
# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)
# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)
# calculate time
result = date_and_time - datetime.timedelta(hours=26, minutes=25, seconds=10)
result.time()
```

Hope it helps

Answered by:**Emily736**| Posted: 07-01-2022

# Answer 3

Look into datetime.timedelta.

```
Example
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
... minutes=50, seconds=600) # adds up to 365 days
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3;
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True
```

Answered by: **Lydia387**| Posted: 07-01-2022

# Answer 4

Look at `mx.DateTime`

, and `DateTimeDelta`

in particular.

```
import mx.DateTime
d = mx.DateTime.DateTimeDelta(0, 1, 23, 10)
x = mx.DateTime.now() + d
x.strftime()
```

Keep in mind that time is actually a rather complicated thing to work with. Leap years and leap seconds are just the beginning...

Answered by:**Julia174**| Posted: 07-01-2022

# Answer 5

The datetime class in python will provide everything you need. It supports addition, subtraction and many other operations.

http://docs.python.org/library/datetime.html

Answered by:**Edgar500**| Posted: 07-01-2022

# Similar questions

datetime - How can I calculate new time zone in python?

Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks

datetime - Howto calculate first date of week and last date for week in python

I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?

datetime - Calculate 9:00 PM in between two dates in python

How can I calculate how many times 9:00 PM can come in between two dates?
dt_start_time = "2014-09-23 11:00:00"
dt_end_time = "2014-09-24 12:00:00"
Expected Output is 1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-24 22:00:00"
Expected Output 1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-26 12:00:00"

datetime - Calculate time span in Python

im using Python v2.x on Windows 64bit
I would like to record two moments in real time and calculate the time span.
Please see code as following:
current_time1 = datetime.datetime.now().time() # first moment
# ... some statement...some loops...take some time...
current_time2 = datetime.datetime.now().time() # second moment
time_span = current_time1 - current_time2
Apparently the ...

python - How to calculate months left to a date with datetime in pandas column?

I want to replace all my the days in my Date column to 01 (the first day of the month) and also calculate the months remaining until a certain date for each of the value in my dataframe.
My dataframe looks like this:
Date
2019-02-10
2017-03-02
2018-02-03
and my date is 2019-10-31. I want to know how many months between these two dates and produce a column with the numb...

In python, using datetime calculate result is error

Using python calculate same time difference on May 4th and May 1st. but get different result
a = datetime(1986, 5, 4, 7, 13, 22).timestamp() - datetime(1986, 5, 4, 0, 0, 0).timestamp()
and
b = datetime(1986, 5, 1, 7, 13, 22).timestamp() - datetime(1986, 5, 1, 0, 0, 0).timestamp()
the results are different, one is 22402.0, another is 26002.0...

python - Pandas - Calculate with datetime column with month and year only

I struggle with a column in a dataframe with only should include month and year.
df["Datum"] = pd.to_datetime(df["Datum"], format="%d.%m.%Y").dt.date
df["Month"] = pd.to_datetime(df['Datum']).dt.strftime('%B-%Y')
I use this column as input for my streamlit app like this:
start_date = df["Month"].min()
end_date = df["Month&...

python - Loop over netCDF datetime format and calculate mean based on month

I have a dataset (a netCDF4 input_file) with the dimensions (504, 720, 500) where the first is a datetime value:
0 1979-01-15
1 1979-02-15
2 1979-03-15
3 1979-04-15
4 1979-05-15
...
499 2020-08-15
500 2020-09-15
501 2020-10-15
502 2020-11-15
503 2020-12-15
Length: 504, dtype: datetime64[ns]
There is a variable with values I want to average per month...

python - How to calculate the number of days left in a given year without using the datetime module?

I am stuck on trying to get the number of days remaining in a given year.
I have already defined a function that determines whether the year is a leap year and how many days in a given month. However, I'm stuck a defining the last function without using the datetime module.
year = int(input("Enter the year to determine the number of days: "))
month = int(input("Enter the month of the ye...

python - Calculate the mean of column A based on a 2 minute time window in Datetime Column

I want to take the average power computed for 2 minute windows based on my time column t which is set as index.
power cadence
t
00:00:00 171.0 74.0
00:00:01 229.0 71.0
00:00:02 229.0 71.0
00:00:03 229.0 71.0
00:00:04 328.0 70.0
... ... ...
01:06:40 0.0 0.0
01:06:41 0.0 0.0
01:06:42 0.0 0.0
01:06:43 0.0 0.0
01:06:44 0.0 ...

datetime - How can I calculate new time zone in python?

Lets say I have a time 04:05 and the timezone is -0100 (GMT)
I want to calculate the new time which will be 03:05
Is there any function in python to do that calculcation ?
Thanks

datetime - Calculate starting time and duration of a digital signal in python

I am having a hard "time" trying to use time and datetime in Python to achive a fairly simple goal. I have already worked with those modules, and have read documentation, but I think I am not getting it the right way.
I have a digital signal (a long array) which represents a time series recorded with a given sampling rate, say, N samples per second.
I have a list of tuples in the f...

datetime - Howto calculate first date of week and last date for week in python

I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?

datetime - Calculate time in a different timezone in Python

I'm working with a dataset with timestamps from two different time zones. Below is what I am trying to do:
1.Create a time object t1 from a string;
2.Set the timezone for t1;
3.Infer the time t2 at a different timezone.
import time
s = "2014-05-22 17:16:15"
t1 = time.strptime(s, "%Y-%m-%d %H:%M:%S")
#Set timezone for t1 as US/Pacific
#Based on t1, calculate the time t2 in a different...

datetime - Calculate 9:00 PM in between two dates in python

How can I calculate how many times 9:00 PM can come in between two dates?
dt_start_time = "2014-09-23 11:00:00"
dt_end_time = "2014-09-24 12:00:00"
Expected Output is 1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-24 22:00:00"
Expected Output 1
dt_start_time = "2014-09-24 09:00:00"
dt_end_time = "2014-09-26 12:00:00"

datetime - Python Pandas: What is the fastest way to calculate days between two date?

I want to calculate elapsed days like this:
df["elapsed_days"] = df.apply(lambda x: (x.logged_day - x.registered_day).days, axis=1)
The type of logged_day and registered_day is datetime.date().
It takes long time to calculate days (maybe) - 40 seconds per 30,0000 records.
Is there anything else I can do to speed things up?
Thank you.

datetime - Python: Calculate hours within a specific time period

I'm working on a script that calculates my salary, for each of my work days, since we don't get the plan send out electronic.
We do earn extra withing some time periods.
every hour i earn 61.86 DKK, but at within some time periods i earn extra money, as seen below.
(For simplicity i have calculated the time in 24h cycle, since that what i am used to)
Weekdays (18:00 - 06:00) 12.20 DKK
S...

arcpy - Calculate Field to remove time from datetime Python

I want to calculate the value of a new field by grabbing the date only (strip out the time) from the existing field DATE_VAL.
I keep getting errors however. Here is my code.
formatter_string = "%m%d%y"
arcpy.CalculateField_management("joined", "Date", dt.strftime("!DATE_VAL!", formatter_string), "PYTHON_9.3", "")
If I try the following:
arcpy.CalculateField_managem...

python - Fastest way to calculate average of datetime rows using pandas

I have 122864 row of data. I am storing data in HDF5 file. Using pandas for data processing. For each unique id in record there is a timestamp associated indicating time when user opened an app. I want to get average duration between two hits of app.
1283 2015-04-01 08:07:44.131768
1284 2015-04-01 08:08:02.752611
1285 2015-04-01 08:08:02.793380
1286 2015-04-01 08:07:53.910469
1287 2015-04-01...

datetime - Calculate time span in Python

im using Python v2.x on Windows 64bit
I would like to record two moments in real time and calculate the time span.
Please see code as following:
current_time1 = datetime.datetime.now().time() # first moment
# ... some statement...some loops...take some time...
current_time2 = datetime.datetime.now().time() # second moment
time_span = current_time1 - current_time2
Apparently the ...

python - What's the best way to calculate a 3D (or n-D) centroid?

As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:
centroid = average(x), average(y), average(z)
where x, y and z are arrays of floating-point numbers. I seem to recall that there is a way to get...

How Python calculate number?

This question already has answers here:

python - Calculate score in a pyramid score system

I am trying to calculate gamescores for a bunch over users and I haven't really got it yet. It is a pyramid game where you can invite people, and the people you invite is placed beneth you in the relations tree.
So if i invite X and X invites Y i get kickback from both of them. Let's say 10%^steps...
So from X i get 10% of his score and 1% from Y, and X get 10% from Y.
So to calculate this i was thi...

How to calculate a mod b in Python?

Is there a modulo function in the Python math library?
Isn't 15 % 4, 3? But 15 mod 4 is 1, right?

To calculate the sum of numbers in a list by Python

My data
466.67
465.56
464.44
463.33
462.22
461.11
460.00
458.89
...
I run in Python
sum(/tmp/1,0)
I get an error.
How can you calculate the sum of the values by Python?

python - How to calculate a date back from another date with a given number of work days

I need to calculate date (year, month, day) which is (for example) 18 working days back from another date. It would be enough to eliminate just weekends.
Example: I've got a date 2009-08-21 and a number of 18 workdays as a parameter, and correct answer should be 2009-07-27.
thanks for any help

python - How to calculate the scrape URL for a torrent

I've read the Bit-torrent specification and done a number of searches, trying to find out how I can get the seeds/peers/downloaded data from a torrent tracker (using Python). I can calculate the info hash from a Torrent no problem, which matches up with the info hash given by various working torrent applications.
However, when I try to get the information from the tracker I either timeout (the tracker is working) o...

c# - Calculate percent at runtime

I have this problem where I have to "audit" a percent of my transtactions.
If percent is 100 I have to audit them all, if is 0 I have to skip them all and if 50% I have to review the half etc.
The problem ( or the opportunity ) is that I have to perform the check at runtime.
What I tried was:
audit = 100/percent
So if percent is 50
audit = 100 /...

python - Calculate time between time-1 to time-2?

enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.

python - How to calculate positions of holes in a game board?

I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one generates the board holes.
Holes are contained in a list/array. Each hole object has a mapping of angles relating to other...

# Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python