Bes
Bes

Reputation: 17

Not able to convert to string

I might be using wrong python terminology.
I have an array of 3 integer elements: month, date and year. However, I am not able to print each individual element when concatenating strings.

import ssl
import OpenSSL
import time
import sys

def get_SSL_Expiry_Date(host, port):
    cert = ssl.get_server_certificate((host, 443))
    x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
    raw_date = x509.get_notAfter()
    decoded_date = raw_date.decode("utf-8")
    dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
    bes = dexpires.tm_mon,dexpires.tm_mday,dexpires.tm_year
    print (bes)
    #print(bes[0]+"/"+bes[1]+"/"+bes[2])

domain = sys.argv[1]
port = 443
get_SSL_Expiry_Date(domain, port)

If I uncomment line 14, I get an error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

I am trying to get the date in this format (all strings): Month/Date/Year.
What am I doing wrong?

Upvotes: 1

Views: 246

Answers (3)

mukesh kudi
mukesh kudi

Reputation: 729

First you have to convert int values to string than only you are able to concave them. You can use str() inbuilt method

print(str(bes[0])+"/"+ str(bes[1])+"/"+ str(bes[2]))  #convert int to str first.

Upvotes: 0

l'L'l
l'L'l

Reputation: 47302

You can use Python's format() method to handle it (much cleaner also):

print("{0}/{1}/{2}".format(bes[0],bes[1],bes[2]))

...or further simplified (thanks Anton)

print("{0}/{1}/{2}".format(*bes))

Python String Formatting

Upvotes: 1

Gnudiff
Gnudiff

Reputation: 4305

Simply use:

print(time.strftime("%m/%d/%y",dexpires))

See also https://docs.python.org/3/library/time.html

In general python modules usually contain all kinds of reformatting functions you don't have to reinvent them.

Example:

>>> dexpires=time.strptime('20180823131455z','%Y%m%d%H%M%Sz')
>>> dexpires
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=23, tm_hour=13, tm_min=14, tm_sec=55, tm_wday=3, tm_yday=235, tm_isdst=-1)
>>> time.strftime('%m/%d/%y',dexpires)
'08/23/18'
>>>

Upvotes: 0

Related Questions