user3349548
user3349548

Reputation: 43

Convert the unicode to datetime format

A function returns date and time in unicode format.

 u'2014-03-06T04:38:51Z'

I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.

Thanks in advance

Upvotes: 2

Views: 26624

Answers (2)

holdenweb
holdenweb

Reputation: 37113

First you have to convert your string to a datetime.datetime object.

import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")

then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.

now = datetime.datetime.now()

Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.

for delta in (now-then, then-now):
    print(delta, "::", delta.days, delta.seconds, delta.microseconds)

This prints out:

-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858

Best try it with a few examples to convince yourself it's correct.

Upvotes: 3

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Check string is unicode

>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True

Converting strings to datetime:

>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)

Subtract from today to

>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)

Upvotes: 4

Related Questions