JohnTaylor JohnTaylor - 5 months ago 20
Python Question

Python Format Date issue

Something which I thought would be simple has become such a struggle.
I'm trying to format a datetime object.

From this 2016-06-17 09:56:53.289000+00:00 to 2016-06-17 09:56:53


This code I tried doesn't make any changes to the output. It skips right past it.

if type(field) is models.DateField:
if old_value != None:
old_value = old_value.strftime('%Y-%m-%d %H:%M:%S')[:-3]
if new_value != None:
new_value = new_value.strftime('%Y-%m-%d %H:%M:%S')[:-3]


Then I tried the following

if isinstance(new_value, datetime.datetime):
new_value = new_value.utcnow().strftime('%Y-%m-%d %H:%M:%S')[:-3]
if isinstance(old_value, datetime.datetime):
old_value = old_value.utcnow().strftime('%Y-%m-%d %H:%M:%S')[:-3]


However it removes any trace of the values of both new_value and old_value and displays nothing. Which is confusing me so much!

The end part of my code is as follows which displays the date:

if new_value != old_value:
print "%s does not match" % key
changes[key] = "Field %s %s updated to %s<br/>" % (key, old_value, new_value)


If anyone could point me in the right direction that would be great.

Answer

Try removing the .utcnow() call you added before your .strftime() calls. new_value.utcnow() invokes datetime.datetime.utcnow, which returns an entirely new datetime.datetime object representing the current time, which has nothing to do with new_value or old_value.

Comments