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
Related
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.
When subtracting two datetime objects, I understand the result is timedelta object:
import datetime
AcDepart = 1900-01-01 18:00:00
AcArrival = 1900-01-01 07:00:00
ActualHours = AcDepart - AcArrival
I want to then subtract the sum of two other date time objects from ActualHours
These are the two other objects:
HrsEarly = 1900-01-01 02:00:00
HrsLate = 1900-01-01 00:30:00
This is the equation that fails to complete:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
This is the error:
UnCalcTime = ActualHours - (HrsEarly + HrsLate)
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
So, I obviously can't add datetime.datetime. Does anyone know how I could get around this? Can timedelta be added together? If so, how can I convert datetime to timedelta?
Any help would be greatly appreciated as I have been trying to solve this unsuccessfully for a long time.
The best solution is to create your variables as timedelta in the first place.
HrsEarly = datetime.timedelta(hours=2)
HrsLate = datetime.timedelta(minutes=30)
If you can't do that, you can simply subtract your "zero date" from the datetime objects.
>>> HrsEarly
datetime.datetime(1900, 1, 1, 2, 0)
>>> HrsEarly = HrsEarly - datetime.datetime(1900, 1, 1)
>>> HrsEarly
datetime.timedelta(0, 7200)
Convert the string to timedelta
from datetime import datetime
AcDepart = '1900-01-01 18:00:00'
AcDepart_ = datetime.strptime(AcDepart, '%Y-%m-%d %H:%M:%S')
AcArrival = '1900-01-01 07:00:00'
AcArrival_ = datetime.strptime(AcArrival, '%Y-%m-%d %H:%M:%S')
ActualHours = (AcDepart_ - AcArrival_).total_seconds()/3600
print ActualHours
It makes no sense to add two datetime objects: It might seem, in your example, that "2AM on the 1st of January 1900" plus "half past midnight on the 1st of January 1900" should be "half past two on the 1st of January 1900", but in another context the desired result could as easily be "half past two on the 2nd of February 3800", or even (if the UNIX epoch is used as an origin) "half past two on the first of January 1830".
Looking at a different example might make this more obvious: what should be the result of Tuesday + Saturday?
Your HrsEarly and HrsLate variables are presumably meant to store a time difference, and there's an appropriate type for that: datetime.timedelta. Adding two of those together does what you want:
>>> from datetime import timedelta
>>> HrsEarly = timedelta(hours=2)
>>> HrsLate = timedelta(minutes=30)
>>> HrsTotal = (HrsEarly + HrsLate)
>>> str(HrsTotal)
'2:30:00'
How about this method using built-in timestamp function?
import datetime
a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = b.timestamp()
d = datetime.timedelta(seconds=c)
Runtime environment
OS: Ubuntu 16.04
Python 3.6
Create a modules.py and paste the following two functions. Import them wherever you want and use as is.
import datetime
def JsTimestampToPyDatetime(js_date):
"""
converts javascript timestamp to python datetime taking care of
milliseconds and seconds
Args:
js_date(Timestamp, required)
Returns:
Datetime
"""
try:
# handles seconds
date = datetime.datetime.fromtimestamp(int(js_date))
except (ValueError):
# handles miliseconds
date = datetime.datetime.fromtimestamp(int(js_date) / 1000)
return date
# consuming javascript generated timestamps
a = JsTimestampToPyDatetime(1627303810000) # with miliseconds
b = JsTimestampToPyDatetime(1627476610) # with seconds only
def GetDaysInDateTime(min_stamp, max_stamp):
"""
Calculates time difference between two timestamps in days
Args:
min_stamp(Datetime, required): Minimum/start datetime
max_stamp(Datetime, required): Maximum/end datetime
Returns:
Int: Days
"""
days = (max_stamp-min_stamp).days
return int(days)
print(GetDaysInDateTime(a, b))
I have spent some time trying to figure out how to get a time delta between time values. The only issue is that one of the times was stored in a file. So I have one string which is in essence str(datetime.datetime.now()) and datetime.datetime.now().
Specifically, I am having issues getting a delta because one of the objects is a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this including the following:
Python - Date & Time Comparison using timestamps, timedelta
Comparing a time delta in python
Convert string into datetime.time object
Converting string into datetime
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following:
2014-01-05 13:09:42.348000
time.strptime returns a struct_time.
datetime.datetime.now() returns a datetime object.
The two can not be subtracted directly.
Instead of time.strptime you could use datetime.datetime.strptime, which returns a datetime object. Then you could subtract now and then.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
By the way, you need to supply a date format string to time.strptime or DT.datetime.strptime.
time.strptime(date)
should have raised a ValueError.
It looks like your date string is 26 characters long. That might mean you have a date string like 'Fri, 10 Jun 2011 11:04:17 '.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like %Y, %m, etc.) here.
Try this:
import time
import datetime
d = datetime.datetime.now()
now = time.mktime(d.timetuple())
And then apply the delta
if you have the year,month,day of 'then' you may use:
year = 2013
month = 1
day = 1
now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)
delta = now_date - then_date
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