I have 2 timestamps derived from OOZIE in this format:
2019-07-20T16:34:45.000Z
and say
2020-08-20T16:20:15.000Z
How can I find the time difference in seconds / mins / days? Which python library can help? Any suggestions?
I don't know about any library, But you can do it yourself.
I am sharing a code that might work.
time_stamp1 = input("Time stamp1")
time_stamp2 = input("Time stamp2")
yrs = int(time_stamp1[:4]) - int(time_stamp2[:4])
mnths = int(time_stamp1[5:7]) - int(time_stamp2[5:7])
days = int(time_stamp1[8:10]) - int(time_stamp1[8:10])
hrs = int(time_stamp1[11:13]) - int(time_stamp2[11:13])
min = int(time_stamp1[14:16]) - int(time_stamp1[14:16])
sec = int(time_stamp1[17:19]) - int(time_stamp1[17:19])
ms = int(time_stamp1[20:23]) - int(time_stamp1[20:23])
print(yrs, mnths, days)
print(hrs, min, sec, ms)
You can use the abs() function if you don't want to know whether timestamp2 is older than timestamp 1 or not or vice versa.
You could use the datetime module.
First, use strptime to convert each of those timestamps into dates. The general format of it is:
from datetime import datetime
date1 = datetime.strptime("2019-07-20T16:34:45.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
date2 = datetime.strptime("2020-08-20T16:20:15.000Z","%Y-%m-%dT%H:%M:%S.%fZ")
(Note: the second argument could be inaccurate, depending on the specifics of OOZIE).
For info on how to construct a format/use strptime, see
this and this for an introduction to strptime.
Then, you could just do t_diff = date1-date2. This will return a timedelta object, with attributes for years, months, weeks, days, etc... microseconds). It also has a builtin .total_seconds() method.
Hope this helped!
Related
Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser
I'm not sure what I need to do to parse them into the same format, but my two dates are:
2017-05-24 15:40:00+00:00
2017-05-24 14:23:44.995015
If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?
Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?
import dateutil.parser
date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
date_delta = date1 - date2 # 1:16:15.004985
You can call replace(microsecond=0) on your dates to remove the microseconds.
You could transform the second datetime (that is a timestamp) into the first one with this code:
def convert_to_timestamp(string_date):
the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
or:
def transformTimestamps(timestamp_):
year = timestamp_[:4]
month = timestamp_[4:6]
day = timestamp_[6:8]
hour = timestamp_[9:11]
minute = timestamp_[11:13]
second = timestamp_[13:15]
microsecond = timestamp_[16:22]
myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
Then, you can calculate the difference between them.
I hope this help. Greetings!
Probably you want to use this method
datetime.strptime(date_string, format)
Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in
class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
microsecond=0, tzinfo=None, *, fold=0)
For more on this topic you can always read the python docs, you can find the same information I just gave you and more here:
https://docs.python.org/3/library/datetime.html
Hope it helped.
I have two date time objects
`statrt_time` and `end_time`
my code is
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
total_seconds=diff.seconds
time_diff = (total_seconds/3600.0)
no_of_units = (time_diff/4)
if(e<s):
self.units = 0
else:
self.units = math.ceil(no_of_units)
Here when I subtract time within the same day it is giving the correct difference. But when the day is changed, it is not calculating the day difference but only giving time difference. How can I add day difference also?
Use total_seconds() instead of seconds.
timedelta.seconds just shows "second" part of the difference, while total_seconds() shows the duration of the difference in seconds. See Mureinik's answer for more details.
So, use this:
total_seconds=diff.total_seconds()
total_seconds is a timedelta object which stores the difference between two datetimes using three fields - days, seconds and miliseconds. Your snippet just uses the seconds attributes instead of the entire difference. The total_seconds() method takes care of this for you and returns, well, the total number of seconds between two datatimes.
I got another way of doing.. BUT A WORK AROUND..
if self.book_from and self.book_to:
fmt = '%Y-%m-%d %H:%M:%S'
s = datetime.strptime(self.book_from,fmt) #start date
e = datetime.strptime(self.book_to,fmt) #end date
diff = e - s
days=diff.days// convert difference to day instead of seconds//
days_seconds=0
if(days>0): //Checking whether the difference exceeds a day//
days_seconds=days*24*3600 //If so convert it to seconds//
total_seconds=diff.seconds+days_seconds
time_diff = (total_seconds/3600.0)
I have a problem that seems really easy but I can't figure it out.
I want to achieve the following:
Time_as_string - time_now = minutes left until time as string.
I scrape a time from a website as a string, for example: '15:30'.
I want to subtract the current time from this to show how many minutes
are left untill the scraped time string.
I tried many things like strftime(), converting to unix timestamp, googling solutions etc.
I can make a time object from the string through strftime() but I can't subtract it from the current time.
What is the best way to achieve this?
from datetime import datetime
s = "15:30"
t1 = datetime.strptime(s,"%H:%M")
diff = t1 - datetime.strptime(datetime.now().strftime("%H:%M"),"%H:%M")
print(diff.total_seconds() / 60)
94.0
If '15:30' belongs to today:
#!/usr/bin/env python3
from datetime import datetime, timedelta
now = datetime.now()
then = datetime.combine(now, datetime.strptime('15:30', '%H:%M').time())
minutes = (then - now) // timedelta(minutes=1)
If there could be midnight between now and then i.e., if then is tomorrow; you could consider a negative difference (if then appears to be in the past relative to now) to be an indicator of that:
while then < now:
then += timedelta(days=1)
minutes = (then - now) // timedelta(minutes=1)
On older Python version, (then - now) // timedelta(minutes=1) doesn't work and you could use (then - now).total_seconds() // 60 instead.
The code assumes that the utc offset for the local timezone is the same now and then. See more details on how to find the difference in the presence of different utc offsets in this answer.
The easiest way is probably to subtract two datetimes from each other and use total_seconds():
>>> d1 = datetime.datetime(2000, 1, 1, 20, 00)
>>> d2 = datetime.datetime(2000, 1, 1, 16, 30)
>>> (d1 - d2).total_seconds()
12600.0
Note that this won't work if the times are in different timezones (I just picked January 1, 2000 to make it a datetime). Otherwise, construct two datetimes in the same timezones (or UTC), subtract those and use total_seconds() again to get the difference (time left) in seconds.
I want to find time difference between two date and then compare the difference time in hours. Something like this,
StartTime = 2011-03-10 15:45:48
EndTime = 2011-03-10 18:04:00
And then find the difference as,
timeDifference = abs(StartTime - EndTime)
And then I need to compare the results as,
If timeDifference > 6 hours
...
When I use this method, the results I got was is in time format, how should I change time format into hours in python?
Thank you,
Let's assume that you have your two dates and times as datetime objects (see datetime.datetime):
>>> import datetime
>>> start_time = datetime.datetime(2011,3,10,15,45,48)
>>> end_time = datetime.datetime(2011,3,10,18,4,0)
Subtracting one datetime from another gives you a timedelta object, and you can use abs to ensure the time difference is positive:
>>> start_time - end_time
datetime.timedelta(-1, 78108)
>>> abs(start_time - end_time)
datetime.timedelta(0, 8292)
Now, to convert the seconds difference from a timedelta into hours, just divide by 3600:
>>> hours_difference = abs(start_time - end_time).total_seconds() / 3600.0
>>> hours_difference
2.3033333333333332
Note that the total_seconds() method was introduced in Python 2.7, so if you want that on an earlier version, you'll need to calculate it yourself from .days and .seconds as in this answer
Update: Jochen Ritzel points out in a comment below that if it's just the comparison with a number of hours that you're interested in, rather that the raw value, you can do that more easily with:
abs(start_time - end_time) > timedelta(hours=6)
What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for ease:
from datetime import datetime
dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )
dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 )
Unfortunately, even after reading the documentation I still do not understand how that line works.
What is the timedelta line doing? How does it work?
Additionally, before I found this stackoverflow post, I was working with time.struct_time tuples. I had a variable tm:
tm = time.strptime(...)
I was simply accessing the hour through tm.tm_hour and subtracting seven from it but this, for obvious reasons, does not work. This is why I am now trying to use datetime. tm now has the value
tm = datetime.strptime(...)
I'm assuming using datetime is the best way to subtract seven hours?
Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this?
What is the timedelta line doing? How does it work?
It creates a timedelta object.
There are two meanings of "time".
"Point in Time" (i.e, date or datetime)
"Duration" or interval or "time delta"
A time delta is an interval, a duration, a span of time. You provided 3 values.
0 days.
2*60*60 + 30*60 seconds.
timedelta() generates an object representing an amount of timeāthe Greek letter delta is used in math to represent "difference". So to compute an addition or a subtraction of an amount of time, you take the starting time and add the change, or delta, that you want.
The specific call you've quoted is for generating the timedelta for 2.5 hours. The first parameter is days, and the second is seconds, so you have (0 days, 2.5 hours), and 2.5 hours in seconds is (2 hours * 60 minutes/hour * 60 seconds/minute) + (30 minutes * 60 seconds / minute).
For your case, you have a negative time delta of 0 days, 7 hours, so you'd write:
timedelta(0, -7 * 60 * 60)
... or timedelta(0, -7 * 3600) or whatever makes it clear to you what you're doing.
Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this?
Yes there is: datetime has built-in timezone conversion capabilities. If you get your datetime object using something like this:
tm = datetime.strptime(date_string, '%Y-%m-%d %H:%M')
it will not have any particular timezone "attached" to it at first, but you can give it a timezone using
tm_utc = tm.replace(tzinfo=pytz.UTC)
Then you can convert it to US/Pacific with
tm_pacific = tm_utc.astimezone(pytz.all_timezones('US/Pacific'))
I'd suggest doing this instead of subtracting seven hours manually because it makes it clear that you're keeping the actual time the same, just converting it to a different timezone, whereas if you manually subtracted seven hours, it looks more like you're actually trying to get a time seven hours in the past. Besides, the timezone conversion properly handles oddities like daylight savings time.
To do this you will need to install the pytz package, which is not included in the Python standard library.