-3

I have a date string formatted like this: "2017-05-31T06:44:13Z".

I need to check whether this date is within a one year span from today's date.

Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?

akhil viswam
  • 496
  • 9
  • 24
  • 5
    _"i can not convert into date object."_ Please clarify. Do you mean "I tried to convert it into a date object, but I could not figure out how"? Or do you mean "I know how to convert it into a date object, but my (teacher | boss | online submission judge) forbids me from doing so"? – Kevin Jun 07 '17 at 13:18
  • i tried to convert into date object using https://stackoverflow.com/questions/9637838/convert-string-date-to-timestamp-in-python .But error ocuured – akhil viswam Jun 07 '17 at 13:22
  • ValueError: time data '2017-05-31T06:44:13Z' does not match format 'yyyy-MM-ddTHH:mm:ssZ' @Kevin – akhil viswam Jun 07 '17 at 13:23

2 Answers2

3

Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.

from datetime import datetime
from dateutil.relativedelta import relativedelta

# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)


if today <= date_to_check <= one_year_from_now:
    #   do whatever
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Use the datetime package together with timedelta:

import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)

and simply check if now-d > then.

Dschoni
  • 3,714
  • 6
  • 45
  • 80