-1

I have the program that generate datetime in several format like below.

1 day, 21:21:00.561566
11:19:26.056148

Maybe it have in month or year format, and i want to know are there any way to plus these all time that i get from the program.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Kaow
  • 483
  • 2
  • 9
  • 22

3 Answers3

2

- 1 day, 21:21:00.561566 is the string representation of a datetime.timedelta object. If you need to parse from string to timedelta, pandas has a suitable method. There are other third party parsers; I'm just using this one since pandas is quite common.

import pandas as pd
td = pd.to_timedelta('- 11:19:26.056148')
# Timedelta('-1 days +12:40:33.943852')
td.total_seconds()
# -40766.056148

If you need to find the sum of multiple timedelta values, you can sum up their total_seconds and convert them back to timedelta:

td_strings = ['- 1 day, 21:21:00.561566', '- 11:19:26.056148']
td_sum = pd.Timedelta(seconds=sum([pd.to_timedelta(s).total_seconds() for s in td_strings]))
td_sum
# Timedelta('-1 days +10:01:34.505418')

...or leverage some tools from the Python standard lib:

from functools import reduce
from operator import add
td_sum = reduce(add, map(pd.to_timedelta, td_strings))
# Timedelta('-1 days +10:01:34.505418')
td_sum.total_seconds()
# -50305.494582
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • 1
    thank for response, actually there is no `-` in font of time, i just edited my code, but anyway i think this is whay i looking for :D – Kaow Jun 04 '20 at 07:41
  • @Kaow: glad I could help. The sign doesn't matter actually, still a timedelta. – FObersteiner Jun 04 '20 at 07:43
0

You can subtract date time like here to find how far apart these two times are:

https://stackoverflow.com/a/1345852/2415706

Adding two dates doesn't really make any sense though. Like, if you try to add Jan 1st of 2020 to Jan 1st of 1995, what are you expecting?

user2415706
  • 932
  • 1
  • 7
  • 19
  • i have a time that i collect, may be 1 day, 2 day, 4 hours or 1 minute and what i want is to calculate the sum of these time so are there any way to do that? – Kaow Jun 04 '20 at 05:27
0

You can use datatime.timedelta class for this purpose.
You can find the documentation here.
You will need to parse your string and build a timedelta object.