0

I'm trying to convert it in a simple way using str() but it doesn't work. How can I do that?

import json
import datetime

def lambda_handler(event, context):
    
    lastUpdate="2020-09-17 03:59:21+00:00"
    now = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
    diff = now - lastUpdate
    print("Now:" + str(now) + lastUpdate)

Output: errorMessage": "unsupported operand type(s) for -: 'datetime.datetime' and 'str'",

3 Answers 3

2

get the utc timezone and string format as below:

from datetime import datetime, timezone

lastUpdate="2020-09-17 03:59:21+00:00"
now2 = datetime.now(timezone.utc).strftime("%Y%m%d  %H:%M:%S")

print("Now:" + str(now2) + lastUpdate)

for the differences, please parse string into two datetime objects and calculate the differences in days.

now3 = datetime.now(timezone.utc)

day = datetime.strptime(lastUpdate, '%Y-%m-%d %H:%M:%S%z')

print("now3= "+ str(now3))
print("day= " +  str(day))
      
diffs = now3 - day

print('Total difference in minutes: ', str(diffs.days))

print("Now:" + str(now3) +" "+ lastUpdate + "Diff= " + str(diffs.days))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. When I do as you do, I get "unsupported operand type(s) for -: 'str' and 'datetime.datetime'". I didn't put diff variable here as it had no issue. How can I resolve this? print("Now:" + now + "LastModified:" + obj['LastModified'] + "Diff=" + diff)
Change everthing into string, Mostlikely your now and diff stil in datetime format. just use str( ) on the datetime object.
1

The datatype of 'now' is datetime and of 'lastUpdate' is str, you cannot get difference between different datatypes. Convert lastUpdate to datetime format first.

import json
from datetime import datetime, timezone
from dateutil import parser

def lambda_handler(event, context):
  lastUpdate="2020-09-17 03:59:21+00:00"
  lastUpdate = parser.parse("2020-09-17 03:59:21+00:00")
  now = datetime.now(timezone.utc)
  diff = now - lastUpdate
  print("Now:" + str(now) + str(lastUpdate))

Comments

1

strftime-and-strptime-behavior

strftime-and-strptime-format-codes

from datetime import datetime

lastUpdate = "2020-09-17 03:59:21+00:00"
dt: datetime = datetime.strptime(lastUpdate, "%Y-%m-%d %H:%M:%S%z")
print(repr(dt))
# datetime.datetime(2020, 9, 17, 3, 59, 21, tzinfo=datetime.timezone.utc)

dt_str = dt.strftime("%Y-%m-%d %H:%M:%S")
print(repr(dt_str))
# '2020-09-17 03:59:21'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.