Home > OS >  How can I convert date to string in python?
How can I convert date to string in python?

Time:10-21

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'",

CodePudding user response:

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))

CodePudding user response:

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'

CodePudding user response:

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))
  • Related