1

I run a sql query that returns a date in the format '2015-03-01T17:09:00.000+0000' I want to subtract this from today's date.

I am getting today's date with the following:

import datetime
now = datetime.datetime.now()

The formats don't seem to line up and I can't figure out a standardize format.

user2242044
  • 8,803
  • 25
  • 97
  • 164
  • possible duplicate of [How to subtract dates with python](http://stackoverflow.com/questions/4863994/how-to-subtract-dates-with-python) – HaveNoDisplayName Dec 24 '14 at 20:07
  • You should probably edit the subject to something like "how to subtract date from date from sql in python" – kartikg3 Dec 24 '14 at 20:13

2 Answers2

2

You can use strptime from datetime module to get python compatible date time from your query result using a format string. (You might have to play with the format string a bit to suit your case)

ts = '2015-03-01T17:09:00.000+0000' to a format string like
f = '%Y-%m-%dT%H:%M:%S.%f%z'
date_from_sql = datetime.datetime.strptime(ts, f)
now = datetime.datetime.now()
delta = date_from_sql - now

The .000 is probably microseconds (denoted by %f in the format string) and the +0000 is the utc offset (denoted by %z in the format string). Check this out for more formatting options: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Check out this thread for an example: what is the proper way to convert between mysql datetime and python timestamp?

Checkout this for more on strptime https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

Community
  • 1
  • 1
kartikg3
  • 2,590
  • 1
  • 16
  • 23
  • Thanks, I read the resources and it makes sense, but I get the error: `ValueError: unconverted data remains: .000+0000` – user2242044 Dec 24 '14 at 20:18
  • The .000 is probably microseconds (denoted by %f in the format string) and the +0000 is the utc offset (denoted by %z in the format string). I have updated the answer. – kartikg3 Dec 24 '14 at 20:48
0

Getting the delta between two datetime objects in Python is really simple, you simply subtract them.

import datetime
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()

delta = d2 - d1
print delta.total_seconds()

d2 - d1 returns a datetime.timedelta object, from which you can get the total second difference between the two dates.

As for formatting the dates, you can read about formatting strings into datetime objects, and datetime objects into string here

You'll read about the strftime() and strptime() functions, and with them you can get yourself two datetime objects which you can subtract from each other.

thomas
  • 1,133
  • 1
  • 12
  • 31