I have a datetime.time object (no date part) in python, and want to find out how many seconds has elapsed since midnight. t.hour * 3600 + t.minute * 60 + t.second will surely work, but is there a more pythonic way?
Unfortunately, it seems you can't get a timedelta object from two datetime.time objects. However, you can build one and use it with total_seconds() to get the number of seconds since midnight:
In [63]: t = datetime.time(hour=12, minute=57, second=12) # for example
In [64]: datetime.timedelta(hours=t.hour, minutes=t.minute,
seconds=t.second).total_seconds()
Out[64]: 46632.0
You could use datetime.combine() to create a datetime object, to get timedelta:
from datetime import datetime, timedelta
td = datetime.combine(datetime.min, t) - datetime.min
seconds = td.total_seconds() # Python 2.7+
integer_milliseconds = td // timedelta(milliseconds=1) # Python 3
It supports microseconds and any other future datetime.time.resolution.
Related
Looking for easiest way to calculate the difference between 2 python times and display the millisecond delta
I have 2 times
startTime = datetime.datetime.now().time()
do some stuff...
endTime= datetime.datetime.now().time()
This works fine and when I log the times out and I get something like this in my logs...
RequestStartTime = 08:56:19.188999
ResponseTime = 08:56:19.905999
When I try to simply subtract them like this
delta = endTime - startTime
I get the following error
unsupported operand type(s) for -: 'time' and 'time'
All I want to do is show the difference in microseconds and I can't figure it out
I want to show is 717000 ms
If you just use the result of now(), and don't convert them to times, you can take the difference & extract the bits you want in the form you want; for example:
startTime = datetime.datetime.now()
endTime= datetime.datetime.now()
delta = endTime - startTime
print str(delta).split(":")[2]
Try this:
from datetime import datetime, date
datetime.combine(date.today(), endTime) - datetime.combine(date.today(), startTime)
Hope this Helps.
To measure the difference manually, you should use time.monotonic() instead.
If you don't care about leap seconds (~1s error once per year and a half) and you need to display the local time:
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
start = datetime.now(timezone.utc).astimezone() # current local time
# print("RequestStartTime = %s" % start.time())
end = datetime.now(timezone.utc).astimezone()
diff_milliseconds = (end - start) / timedelta(milliseconds=1)
print("%.0f ms" % diff_milliseconds)
The code works fine around/during DST transitions.
Note: it is different from the code that uses just .now(). If you use .now() (no argument) then you get a naive datetime object that represents local time and in that case if a DST transition happens between start and end times then end - start returns a completely wrong result i.e., the code may be wrong by an hour approximately couple of times per year in some timezones.
the reason why you are getting an error is because class time does not support subtraction. You must turn time into miliseconds (int format) to subtract from one another.
instead of using datetime, use time
import time
def timenow():
return int(round(time.time() * 1000))
startTime = timenow()
time.sleep(1)
endTime = timenow()
delta = endTime - startTime
print delta
The simplest solution would be to convert the datetime objects to timestamps and subtract those. If you use Python 3.3 or later you can simply do something along these lines
startTime = datetime.datetime.now(timezone.utc).timestamp()
...
endTime = datetime.datetime.now(timezone.utc).timestamp()
Then you can just subtract those.
In Python 2 you do not have the timestamp method available. One way around would be to use a timedelta object:
startTime = datetime.datetime.now(timezone.utc)
...
endTime = datetime.datetime.now(timezone.utc)
dt = (endTime - startTime).total_seconds()
A third option is to simply use raw timestamps with time.time() and subtract them to get the time interval in seconds and fraction of seconds.
To be extra safe you could use time.monotonic() as #Sebastian mentions.
This is the best answer for this problem:
https://stackoverflow.com/a/39651061/2686243
from datetime import datetime, date
duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)
How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
For Python 2 code, use datetime.utcnow():
from datetime import datetime
datetime.utcnow()
For Python 3, use datetime.now(timezone.utc) (the 2.x solution will technically work, but has a giant warning in the 3.x docs):
from datetime import datetime, timezone
datetime.now(timezone.utc)
For your purposes when you need to calculate an amount of time spent between two dates all that you need is to subtract end and start dates. The results of such subtraction is a timedelta object.
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's definition -
days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:
Return the total number of seconds contained in the duration.
Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) *
106) / 106 computed with true division enabled.
Timezone-aware datetime object, unlike datetime.utcnow():
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Timestamp in milliseconds since Unix epoch:
datetime.now(timezone.utc).timestamp() * 1000
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow
import datetime
import pytz
# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)
# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp()
# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000)
Timezone aware with zero external dependencies:
from datetime import datetime, timezone
def utc_now():
return datetime.utcnow().replace(tzinfo=timezone.utc)
From datetime.datetime you already can export to timestamps with method strftime. Following your function example:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return int(now.strftime("%s"))
If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))
you could use datetime library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))
why all reply based on datetime and not time?
i think is the easy way !
import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)
To be correct, UTC format needs at least the T letter:
>>> a=(datetime.datetime.now(timezone.utc))
>>> a.strftime("%Y-%m-%dT%H:%M:%SZ")
'2022-11-28T16:42:17Z'
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python datetime to Unix timestamp
Is there a way to convert a datetime to int, representing the minutes since, for example, January 2012, so that this int can be modified, written to a database, compared and so on?
EDIT:
The server I am running this on uses Python 2.6.6
Subtracting two datetime.datetime objects gives you a timedelta object, which has a .total_seconds() method (added in Python 2.7). Divide this by 60 and cast to int() to get minutes since your reference date:
import datetime
january1st = datetime.datetime(2012, 01, 01)
timesince = datetime.datetime.now() - january1st
minutessince = int(timesince.total_seconds() / 60)
or in a python shell:
>>> import datetime
>>> january1st = datetime.datetime(2012, 01, 01)
>>> timesince = datetime.datetime.now() - january1st
>>> minutessince = int(timesince.total_seconds() / 60)
>>> minutessince
346208
For python 2.6 and earlier, you'll have to use the .days and .seconds attributes to calculate the minutes:
minutessince = timesince.days * 1440 + timesince.seconds // 60
which gives you an integer as well.
By substracting datetimes, you can have a timedelta. This timedelta can be divided itself to give you what you want :
(datetime.datetime.now() - datetime.datetime(2012, 1, 1)) // datetime.timedelta(minutes=1)
(this code is only valid with python3, and that's why everybody should switch to python3 ;-) )
If you want the minutes of the delta between two dates, you can make a datetime.timedelta object by subtracting the two dates (see here), and then retrieve the minutes as shown in this question:
Convert a timedelta to days, hours and minutes
>>> import datetime
>>> now = datetime.datetime.now()
>>> then = datetime.datetime(year=2012, month=1, day=1)
>>> delta=now-then
This is a timedelta object representing an interval of time.
>>> print delta
240 days, 11:05:25.507000
To count the minutes during that interval, use:
>>> print delta.total_seconds() / 60
346265.42511666665
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
This seems to be only differentiating between dates that have different days:
t.toordinal()
How does one convert a datetime object to seconds?
For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.
>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0
The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.
As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.
Starting from Python 3.3 this becomes super easy with the datetime.timestamp() method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.
To get the Unix time (seconds since January 1, 1970):
>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0
Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:
>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0
# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)
Note that different timezones have impact on results, e.g. my current TZ/DST returns:
>>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h
therefore one should consider normalizing to UTC by using UTC versions of the functions.
Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.
References:
datetime.date.timetuple
time.mktime
datetime.datetime.fromtimestamp
introduction in time module explains POSIX time, 1970 epoch, UTC, TZ, DST ...
int (t.strftime("%s")) also works
from the python docs:
timedelta.total_seconds()
Return the total number of seconds contained in the duration. Equivalent to
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
computed with true division enabled.
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
This functionality is new in version 2.7.
Comparing the 4 most common ways to do this, for accuracy:
Method 1: Manual Calculation
from datetime import datetime
total1 = int(datetimeobj.strftime('%S'))
total1 += int(datetimeobj.strftime('%M')) * 60
total1 += int(datetimeobj.strftime('%H')) * 60 * 60
total1 += (int(datetimeobj.strftime('%j')) - 1) * 60 * 60 * 24
total1 += (int(datetimeobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
print ("Method #1: Manual")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total1)
print ("After: %s" % datetime.fromtimestamp(total1))
Output:
Method #1: Manual
Before: 1970-10-01 12:00:00
Seconds: 23630400
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 2: Time Module
import time
from datetime import datetime
total2 = int(time.mktime(datetimeobj.timetuple()))
print ("Method #2: Time Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total2)
print ("After: %s" % datetime.fromtimestamp(total2))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Method 3: Calendar Module
import calendar
from datetime import datetime
total3 = calendar.timegm(datetimeobj.timetuple())
print ("Method #3: Calendar Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total3)
print ("After: %s" % datetime.fromtimestamp(total3))
Output:
Method #3: Calendar Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 4: Datetime Timestamp
from datetime import datetime
total4 = datetimeobj.timestamp()
print ("Method #4: datetime timestamp")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total4)
print ("After: %s" % datetime.fromtimestamp(total4))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Conclusion
All 4 methods convert datetime to epoch (total seconds)
Both the Manual method and Calendar module method are time zone aware.
Both datetime.timestamp() and time.mktime() methods are time zone unaware.
Simplest method: datetime.timestamp()
I do not see this in all of the answers, although I guess it is the default need:
t_start = datetime.now()
sleep(2)
t_end = datetime.now()
duration = t_end - t_start
print(round(duration.total_seconds()))
If you do not use .total_seconds(), it throws: TypeError: type datetime.timedelta doesn't define __round__ method.
Example:
>>> duration
datetime.timedelta(seconds=53, microseconds=621861)
>>> round(duration.total_seconds())
54
>>> duration.seconds
53
Taking duration.seconds takes only the seconds, leaving aside the microseconds, the same as if you ran math.floor(duration.total_seconds()).
To convert a datetime object that represents time in UTC to POSIX timestamp:
from datetime import timezone
seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()
To convert a datetime object that represents time in the local timezone to POSIX timestamp:
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()
See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.
Follow the links if you need solutions for <3.3 Python versions.
I tried the standard library's calendar.timegm and it works quite well:
# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
return int(calendar.timegm(aDateTime.timetuple())*1000)
Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm
Python provides operation on datetime to compute the difference between two date. In your case that would be:
t - datetime.datetime(1970,1,1)
The value returned is a timedelta object from which you can use the member function total_seconds to get the value in seconds.
(t - datetime.datetime(1970,1,1)).total_seconds()
import datetime
import math
def getSeconds(inputDate):
time = datetime.date.today().strftime('%m/%d/%Y')
date_time = datetime.datetime.strptime(time, '%m/%d/%Y')
msg = inputDate
props = msg.split(".")
a_timedelta = datetime.timedelta
if(len(props)==3):
a_timedelta = date_time - datetime.datetime(int(props[0]),int(props[1]),int(props[2]))
else:
print("Invalid date format")
return
seconds = math.trunc(a_timedelta.total_seconds())
print(seconds)
return seconds
Example getSeconds("2022.1.1")
The standard way to find the processing time in ms of a block of code in python 3.x is the following:
import datetime
t_start = datetime.datetime.now()
# Here is the python3 code, you want
# to check the processing time of
t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.
The datetime library has a timedelta object specifically for this kind of thing:
import datetime
mydatetime = datetime.now() # or whatever value you want
twelvelater = mydatetime + datetime.timedelta(hours=12)
twelveearlier = mydatetime - datetime.timedelta(hours=12)
difference = abs(some_datetime_A - some_datetime_B)
# difference is now a timedelta object
# there are a couple of ways to do this comparision:
if difference > timedelta(minutes=1):
print "Timestamps were more than a minute apart"
# or:
if difference.total_seconds() > 60:
print "Timestamps were more than a minute apart"
You'd use datetime.timedelta for something like this.
from datetime import timedelta
datetime arithmetic works kind of like normal arithmetic: you can add a timedelta object to a datetime object to shift its time:
dt = # some datetime object
dt_plus_12 = dt + timedelta(hours=12)
Also you can subtract two datetime objects to get a timedelta representing the difference between them:
dt2 = # some other datetime object
ONE_MINUTE = timedelta(minutes=1)
if abs(dt2 - dt) > ONE_MINUTE:
# do something