0

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?

Davtho1983
  • 3,827
  • 8
  • 54
  • 105

3 Answers3

2

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.

zwer
  • 24,943
  • 3
  • 48
  • 66
0

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!

0

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.

Franco Roura
  • 807
  • 8
  • 26