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?
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
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'
>>>
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.
Related
Hi I'm a newbie learning python and I want to print something only if current time starts with x (for example, if current time starts with = 4, print "hi", time = 4:18), this is the code I made, it says attribute error:
import datetime
local = datetime.datetime.now().time().replace(microsecond=0)
if local.startswith('16'):
print("Hi! It's ", local)
The .replace() method returns a date object. date objects don't have a .startswith() method. That method is only for str.
Try converting your date to a string first:
if str(local).startswith('16'):
print("Hi! It's ", local)
The documentation lists all of the methods available on a date object.
You need to first convert it to a string, as datetime objects have no startswith() method. Use strftime, example:
import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t2 = t.strftime('%m/%d/%Y')
will yield:
'02/23/2012'. Once it's converted, you can use t2.startswith().
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
You can get the hour of the time and check if it is 16:
if local.hour == 16:
print("Hi! It's ",local)
If you need to use startswith() then you can convert it to a string like this:
if str(local).startswith('16'):
print("Hi! It's ", local)
That's not a good way. Check the time as int is the better solution here.
replace() has 2 needed str arguments. You use a named attribute which doesn't exist.
I'm writing a python script to convert data from csv to geojson, which is working.
I have a field in the date format ( "2017-07-14 17:01:00") but fro this data I only need the hours part (17 only) so I'm trying to substring it to get only that part, I added that function:
def substr(strtime):
strtime = strtime.Substr(strtime, 0, 3)
return substr(strtime)
And I'nm getting that error meaage
AttributeError: 'str' object has no attribute 'Substr'
Does any body have an idea about how to fix it?
Strings in python can be treated as char arrays so you can access like this:
myStr=strtime[0:3]
Use datetime module.
Ex:
import datetime
def substr(strtime):
strtime = datetime.datetime.strptime(strtime, "%Y-%m-%d %H:%M:%S")
return strtime.strftime("%H")
print( substr( "2017-07-14 17:01:00") )
If you do not want to use datetime module you can do.
def substr(strtime):
return strtime[11:13]
Output:
17
I have a db query that returns tuple as below
[6,6,6,5,5,5,4,4]
[10,10,10,11,11,11]
[3597590, 3597588,3597558,3597544,3597590]
I would like to get the average of each set. I tried to sum them using different ways for example
for row in cur.fetchall(
x = row[4]
print map(sum, x)
it throws an error
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I try to convert to int but also throws error
ValueError: invalid literal for int() with base 10: '['
looks like you have a string representing a list of integers, in that case you can use the ast module, more precisely the ast.literal_eval function to transform it to an actual list and sum it
>>> import ast
>>> test = "[3597590, 3597588,3597558,3597544,3597590]"
>>> x=ast.literal_eval(test)
>>> x
[3597590, 3597588, 3597558, 3597544, 3597590]
>>> sum(x)
17987870
>>>
if what you get is a string that looks as your example, then you can use the splitlines method to get each line
>>> test2="""[6,6,6,5,5,5,4,4]
[10,10,10,11,11,11]
[3597590, 3597588,3597558,3597544,3597590]"""
>>> lines = test2.splitlines()
>>> lines
['[6,6,6,5,5,5,4,4]', '[10,10,10,11,11,11]', '[3597590, 3597588,3597558,3597544,3597590]']
>>> map(sum,map(ast.literal_eval,lines))
[41, 63, 17987870]
>>>
as mention in the comments, the json module is another option
>>> import json
>>> test
'[3597590, 3597588,3597558,3597544,3597590]'
>>> json.loads(test)
[3597590, 3597588, 3597558, 3597544, 3597590]
>>>
The answer from #Copperfield is likely the right way to do it for the problem as stated.
That said, I think you should deal with the problem upstream rather than in Python. Use the SQL SUM and AVERAGE functions inside your query so that the work is done by the SQL engine.
I am getting input from an external device connected via Ethernet, and it is passing several values of string type e.g. value = '(2,2)\n'. I would like to assign these values to a list or tuple variable e.g. final_value = (2,2).
The code I am using is the following:
import socket
sock = socket.socket()
value =sock.recv(buffersize=2048)
formatted_value = eval(value)
I read that the eval function I am using at this moment to get the list is not a very safe approach, as the external device could pass a dangerous script. So, I would like to know if there is any alternative, similar to the function int(), which can be used to get an integer from a string.
Use ast module literal_eval method for a safer eval
import ast
formatted_value = ast.literal_eval(value)
If you know the input contains a tuple
from ast import literal_eval as make_tuple
make_tuple(value)
Well to give the alternative approach you can do.
s = '(2, 2)\n'
s = s.strip()
if s.startswith('(') and s.endswith(')'):
tup = tuple(int(i) for i in s[1:-1].split(','))
print(tup)
Or if you want a list
s = '(2, 2)\n'
s = s.strip()
if s.startswith('(') and s.endswith(')'):
lst = [int(i) for i in s[1:-1].split(',')]
print(lst)
Is there a script available to convert a starting and ending IP address to a slash notation?
Example:
>>> ip_long = '10.182.71.0-10.182.75.255'
>>> convert_to_slash(ip_long)
10.182.71.0/24, 10.182.72.0/22
Use summarize_address_range() from ipaddress, which is part of the Python 3 standard library (and backported to Python 2).
>>> import ipaddress
>>> first = ipaddress.IPv4Address('10.182.71.0')
>>> last = ipaddress.IPv4Address('10.182.75.255')
>>> summary = ipaddress.summarize_address_range(first, last)
>>> list(summary)
[IPv4Network('10.182.71.0/24'), IPv4Network('10.182.72.0/22')]
Google's ipaddr-py library has a method called summarize_address_range(first, last).
summarize_address_range(first, last):
"""Summarize a network range given the first and last IP addresses.
Example:
>>> summarize_address_range(IPv4Address('1.1.1.0'),
IPv4Address('1.1.1.130'))
[IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
IPv4Network('1.1.1.130/32')]
Args:
first: the first IPv4Address or IPv6Address in the range.
last: the last IPv4Address or IPv6Address in the range.
Returns:
The address range collapsed to a list of IPv4Network's or
IPv6Network's.
Raise:
TypeError:
If the first and last objects are not IP addresses.
If the first and last objects are not the same version.
ValueError:
If the last object is not greater than the first.
If the version is not 4 or 6.
"""
Another solution:
from ipaddress import IPv4Address, summarize_address_range
a=" ".join(map(str, summarize_address_range(IPv4Address('8.8.8.8'), IPv4Address('8.8.9.1'))))
print(a)