Convert timedelta to total seconds - python

I have a time difference
import time
import datetime
time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
...
time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
diff = time2 - time1
Now, how do I find the total number of seconds that passed? diff.seconds doesn't count days. I could do:
diff.seconds + diff.days * 24 * 3600
Is there a built-in method for this?

Use timedelta.total_seconds().
>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.
(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.
(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:
gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.
I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31
>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time
You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):
from datetime import datetime
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
time2 = datetime.strftime('19 01 2021', '%d %m %Y')
difference = time2 - time1
difference_in_seconds = difference.total_seconds()

You can use mx.DateTime module
import mx.DateTime as mt
t1 = mt.now()
t2 = mt.now()
print int((t2-t1).seconds)

Related

How to add times that has HH:MM:SS,XX format in python

My expertise lack when it comes to understanding this time format. I am guessing the ,XXX is XXX/1000 of a second?
Nevertheless I am trying to add a text files that contains time stamp like these and sum up the total.
Below is an example,
00:03:33,950
00:03:34,590
This is what I have so far but I'm not sure how to add up the last part
Hours = s.split(":")[0]
Minutes = s.split(":")[1]
Seconds = (s.split(":")[2]).split(",")[0]
Total_seconds = (Hours * 3600) + (Minutes * 60) + (Seconds)
Total_Time = str(datetime.timedelta(seconds=Total_seconds))
Reed this documentation about time.strftime() format
For example
from time import gmtime, strftime
strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
--'Thu, 28 Jun 2001 14:17:15 +0000'--
Actually, you're halfway there.
All you have to do is to to convert your strs into int and pass them as parameters to the appropriate timedelta keywords.
from datetime import timedelta
Hours = int(s.split(":")[0])
Minutes = int(s.split(":")[1])
Seconds = int((s.split(":")[2]).split(",")[0])
Milliseconds = int((s.split(":")[2]).split(",")[1])
duration = timedelta(hours=Hours, minutes=Minutes, seconds=Seconds, milliseconds=Milliseconds)
After adding all the durations you need, str() the final timedelta object.
>>> durations_1 = timedelta(hours=2,milliseconds=750)
>>> durations_2 = timedelta(milliseconds=251)
>>> durations_sum = durations_1 + durations_2
>>> str(durations_sum)
'2:00:01.001000'
>>> str(durations_sum).replace('.',',')
'2:00:01,001000'

Datetime Format and calculation

I'm trying to make a simple system which would get the current time and get another time after few secs, then see the difference with both of the times, so it's 2 seconds. So what I need is the other format like this > YEAR,MONTH,DAY HOUR:MIN.
This is the code which I use for this purpose, but in brackets there are just an example of the format I need.
a = datetime.datetime.now( %Y, %m %d %H:%M)
time.sleep(2)
b = datetime.datetime.now( %Y, %m %d %H:%M)
print(b-a)
print(a)
print(b)
I thing strftime is what you're looking for
import datetime
import time
a = datetime.datetime.now()
time.sleep(2)
b = datetime.datetime.now()
print(b-a)
print(a.strftime("%Y, %m, %d %H:%M"))
print(b.strftime("%Y, %m, %d %H:%M"))
prints
0:00:02.001719
2019, 09, 04 15:17
2019, 09, 04 15:17
For more formats, you can see strftime reference: https://www.programiz.com/python-programming/datetime/strftime.
You can convert a datetime.datetime instance to a string formatted to your liking using the strftime() function. For instance, to print with your preferred formatting you could do the following:
>>> import datetime
>>> a = datetime.datetime.now()
>>> print(a.strftime("%Y, %m %d %H:%M")
2019, 09 04 17:11
Subtracting two dates will yield a datetime.timedelta object, you can convert this to the number of seconds using the total_seconds() function:
>>> import datetime
>>> from time import sleep
>>> a = datetime.datetime.now()
>>> sleep(2)
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print(delta.total_seconds())
2.001301

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 time zone
#(e.g, Central European Time(CET))
Any answers/comments will be appreciated..!
Use datetime and pytz
import datetime
import pytz
pac=pytz.timezone('US/Pacific')
cet=pytz.timezone('CET')
s = "2014-05-22 17:16:15"
t1 = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
pacific = pac.localize(t1)
cet_eur = pacific.astimezone(cet)
print pacific
print cet_eur
2014-05-22 17:16:15-07:00
2014-05-23 02:16:15+02:00
I think you want datetime.timetuple
Return a time.struct_time such as returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple() is equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)), where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.
print datetime.date.timetuple(t1)
time.struct_time(tm_year=2014, tm_mon=5, tm_mday=22, tm_hour=17, tm_min=16, tm_sec=15, tm_wday=3, tm_yday=142, tm_isdst=-1)
That is a quick draft but the pytz docs have lots of good and clear examples

Count occurrences of midnight between datetimes

Is there a native facility or third party library for python that can count the number of occurrences of a time (in particular the number of midnights) between two datetimes?
It is not sufficient to count the number of days because the datetimes might not have the same time component, so you end up with the kind of intervals shown in this example:
from datetime import datetime as dt
dt1 = dt(2014,05,21,23)
dt2 = dt(2014,05,22,01)
i1 = dt2-dt1
print(i1) # 1 midnight but 2 hours
dt3 = dt(2014,05,21,01)
dt4 = dt(2014,05,22,23)
i2 = dt4-dt3 # 1 midnight but 1 day + 22 hours
print(i2)
Set the time component of both datetimes to the same time, then do the difference.
def midnights(dt1, dt2):
dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0)
dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0)
return (dt2 - dt1).days
Use .date() for the difference:
from datetime import datetime as dt
def count_midnights(dt1, dt2):
return (dt2.date() - dt1.date()).days
This way you get:
>>> dt1 = dt(2014,05,21,23)
>>> dt2 = dt(2014,05,22,01)
>>> print count_midnights(dt1, dt2)
1
>>> dt3 = dt(2014,05,21,01)
>>> dt4 = dt(2014,05,22,23)
>>> print count_midnights(dt3, dt4)
1
Just a bit crazy alternative, mostly FYI, - you can use a nice Delorean third-party:
from datetime import datetime as dt
import delorean
from delorean import stops
dt1 = dt(2014,05,21,23)
dt2 = dt(2014,05,22,01)
print sum(1 for stop in stops(start=dt1, stop=dt2, freq=delorean.HOURLY)
if stop.datetime == stop.midnight())

Does Python's time.time() return the local or UTC timestamp?

Does time.time() in the Python time module return the system's time or the time in UTC?
The time.time() function returns the number of seconds since the epoch, as a float. Note that "the epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where on Earth you are, "seconds past epoch" (time.time()) returns the same value at the same moment.
Here is some sample output I ran on my computer, converting it to a string as well.
>>> import time
>>> ts = time.time()
>>> ts
1355563265.81
>>> import datetime
>>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
'2012-12-15 01:21:05'
>>>
The ts variable is the time returned in seconds. I then converted it to a human-readable string using the datetime library.
This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:
>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000
The now differs from utcnow as expected -- otherwise they work the same way:
>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000
You can render the timestamp to the string explicitly:
>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'
Or you can be even more explicit to format the timestamp the way you like:
>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'
If you want the ISO format, use the .isoformat() method of the object:
>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'
You can use these in variables for calculations and printing without conversions.
>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980
Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.
>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318
At least that's the concept.
The answer could be neither or both.
neither: time.time() returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch".
both: time.time() doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):
from datetime import datetime
utc_dt = datetime.utcfromtimestamp(timestamp)
On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?
To get a local timestamp using datetime library, Python 3.x
#wanted format: year-month-day hour:minute:seconds
from datetime import datetime
# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')
# print it to screen
print(timeStamp)
I eventually settled for:
>>> import time
>>> time.mktime(time.gmtime())
1509467455.0
There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.
timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.
>>> import time, datetime
>>> time.time()
1564494136.0434234
>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)
There exist nice library arrow with different behaviour. In same case it returns you time object with UTC timezone.
>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>
time.time() return the unix timestamp.
you could use datetime library to get local time or UTC time.
import datetime
local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))

Categories