Python defined variables with dates as "string", how do I convert it to the right type for comparison?

Dates in variables:

today - 2019,01,16

server - 2018,11,11

import subprocess import datetime from datetime import datetime, date, timedelta server = subprocess.check_output("ΠΊΠΎΠΌΠ°Π½Π΄Π°_ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ", shell=True).decode('utf-8').strip() today = datetime.today().strftime("%Y,%m,%d") startDay = (today-server) print(startDay.days) 

Conclusion:

 Traceback (most recent call last): File "test.py", line 15, in <module> startDay = (today-server) TypeError: unsupported operand type(s) for -: 'str' and 'str' 
  • Please add the entire stack with an error in the question. And so, I understand the error in today-server - gil9red 1:54 pm
  • Traceback (most recent call last): File "test.py", line 15, in <module> startDay = (today-server) TypeError: unsupported operand type (s) for -: 'str' and 'str' - vlad
  • one
    Try replacing startDay = (today-server) with startDay = datetime.strptime(today, "%Y,%m,%d") - datetime.strptime(server, "%Y,%m,%d") - S Nick
  • one
    Thank you very much, it works! startDay = datetime.strptime (today, "% Y,% m,% d") - datetime.strptime (server, "% Y,% m,% d") - vlad
  • To compare the date, you can not convert anywhere: if the date goes in the order year-month-day, then you can directly compare the string '2019,01,16' > '2018,11,11' - insolor

2 answers 2

Just work with date types, i.e. bring server to date type:

 import subprocess from datetime import datetime server = subprocess.check_output("ΠΊΠΎΠΌΠ°Π½Π΄Π°_ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ", shell=True).decode('utf-8').strip() server = datetime.strptime(server, "%Y,%m,%d") today = datetime.today() startDay = today - server print(startDay.days) # 66 
  • The server variable was converted, but the problem arose, why today in string? today = datetime.today (). strftime ("% Y,% m,% d") print (type (today)) <class 'str'> - vlad
  • 2
    Because strftime converts a date to a string. - Enikeyschik

In this case, the date format matches the order of the arguments in the datetime.datetime () constructor β€” you can use this:

 In [34]: from datetime import datetime In [35]: today = '2019,01,16' In [36]: d = datetime(*list(map(int, today.split(',')))) In [37]: d Out[37]: datetime.datetime(2019, 1, 16, 0, 0) In [38]: print(d) #2019-01-16 00:00:00