Time difference with different time formats in Python3 - python

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.

Related

Get previous day's date from date passed as a string in "YYYY-MM-DD" format

I'm trying to create a helper function getPreviousDay to be used in the backend (Flask).
From the front end, I'm receiving the date in "YYYY-MM-DD" format as a string.
From this, I want to get the date of the previous day in the same format as a string.
Here's a sample code of what I want to achieve.
def getPreviousDay(date):
'''
todo: previousDay should also be a string in "YYYY-MM-DD" format
'''
return previousDay
current_day = "2022-09-29" #YYYY-MM-DD
yesterday = getPreviousDay(current_day)
The datetime module provides date and timedelta types that can be used for this kind of thing. A "time delta" is a difference between two dates or times, in this case, 1 day. Subtracting one day from today's date gives yesterday's date.
import datetime
def getPreviousDay(date):
today = datetime.date.fromisoformat(date)
yesterday = today - datetime.timedelta(days=1)
return yesterday.isoformat()
This returns:
>>> getPreviousDay('2022-09-29')
'2022-09-28'
The reference documentation for the datetime module has more details.

What would be the best way to compute OOZIE timestamp difference?

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!

Using the time functions

I have a small question. I have an array that saves dates in the following format.
'01/02/20|07/02/20'
It is saved as a string, which uses the start date on the left side of the "|" and end date on the other side.
It is only the end date that matters here, but is there a function or algorithm I can use to automatically calculate the difference in days and months between now.datetime and the end date (right-hand side of "|")?
Thanks, everyone
datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:
In [34]: from datetime import datetime
In [35]: end_date = datetime.strptime(s.split('|')[1], '%d/%m/%y')
In [36]: diff = datetime.now() - end_date
In [37]: diff
Out[37]: datetime.timedelta(days=81, seconds=81712, microseconds=14069)
In [38]: diff.days
Out[38]: 81
You might be looking for something like this.
Python datetime module is the way to go for a problem like this
import datetime
dates = '01/02/20|07/02/20'
enddate = dates.split('|')[-1]
# Use %y for 2 digits year else %Y for 4 digit year
enddate = datetime.datetime.strptime(enddate, "%d/%m/%y")
today = datetime.date.today()
print(abs(enddate.date() - today).days)
Output:
81

Want to find difference, in days, between two dates, of different date format, in Python

I have two different dates that I am pulling from a database using a SQL query. Im looking to do transformations in Python, but the two main dates I want to work with are stored in different formats. The first date is of the date format (YYYY/MM/DD) the other is of (YYYY/MM/DD HH:MM:SS) format. I want a difference in days so the DATETIME is irrelevant on the second date. I was wondering what is the easiest way to do this in python? Ideally, I would like to automate this, where I create a DATE format of the DATETIME variable, and take the difference between the two DATES.
I've tried the following but I am also getting errors since I am dealing with Series. I am trying to get the delta for every row.
df.delta = (df.DATETIME - df.DATE)
and
df.delta = datetime.timedelta(df.DATETIME - df.DATE)
import datetime
d1 = datetime.datetime.strptime('2018/01/13', '%Y/%m/%d')
d2 = datetime.datetime.strptime('2018/01/15 18:34:02', '%Y/%m/%d %H:%M:%S')
delta = d2 - d1
print delta.total_seconds()
print delta.days
Convert your datetime object to a date object, you are then able to subtract them for a delta value.
df.delta = (df.DATETIME.date() - df.DATE)

When I substract two datetime object in python it is considering only time not taking day

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)

Categories