Python string to timestamp - python

I am trying to convert these strings to timestamps:
python test.py
2015-02-15T14:25:54+00:00
2015-02-15T16:59:01+00:00
2015-02-15T18:44:13+00:00
2015-02-15T18:45:24+00:00
2015-02-15T18:52:11+00:00
2015-02-15T18:52:33+00:00
2015-02-15T18:59:00+00:00
2015-02-15T19:06:16+00:00
2015-02-15T19:07:02+00:00
I get this output on executing below code:
for member in members_dict['members']:
s = member['timestamp_signup']
print s
But when I try to get the timestamp:
for member in members_dict['members']:
s = member['timestamp_signup']
print s
print time.mktime(datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S+00:00").timetuple())
I get the error as:
Traceback (most recent call last):
File "test.py", line 20, in <module>
print datetime.strptime(s, '"%Y-%m-%dT%H:%M:%S+00:00"').date()
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '' does not match format '"%Y-%m-%dT%H:%M:%S+00:00"'
What am I doing wrong here?

Your code to convert string to datetime is fine. For example:
>>> from datetime import datetime
>>> my_str = '2015-02-15T14:25:54+00:00'
>>> datetime.strptime(my_str, "%Y-%m-%dT%H:%M:%S+00:00")
datetime.datetime(2015, 2, 15, 14, 25, 54)
Error you are getting is due to empty string present in your file. I got to know about it based on your error message:
ValueError: time data '' does not match format
# empty string ^
Possibly there is empty line at the end of your file (or, somewhere else)

Related

Abbreviated month or day of the week with a DOT (".") at the end of the string

I need to change with python a lot of strings with a Spanish date format (DDMMMYYYY, MMM abbreviated month in Spanish) in a other datetime format but I'm having problems because my locale Spanish settings has a "." (a dot) at the end of the string when it change this format in a abbreviated month format.
By default, python take the English version of the language but I can change the language with the locale library.
When I select 'esp' or 'es_ES.utf8' the dot at the end of the abbreviated month appears.
Does it depend on the regional settings of my Windows 10? (I check it and all seems OK) Does it depend on the LOCALE library settings?
The same code in UBUNTU runs OK (without the point)
How can I solve this problem?
I don't want to transform all the strings like that..
str_date = str_date[:5] + "." + str_date[5:]
Thanks a lot!!
Example (previously I change the language with locale):
>>> datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b')
'ene.'
>>> print(datetime.strptime('18ene2021', '%d%b%Y'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\galonsoi\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Users\galonsoi\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '18ene2021' does not match format '%d%b%Y'
>>> print(datetime.strptime('18ene.2021', '%d%b%Y'))
2021-01-18 00:00:00 ----> THIS IS OK BECAUSE I WRITE THE DOT AT THE END OF THE ABBREVIATED MONTH
Complete sequence of the Example
>>> import locale
>>> from datetime import datetime
>>>
>>> locale.getlocale()
(None, None)
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
Jan
>>> locale.setlocale(locale.LC_ALL, '')
`Spanish_Spain.1252`
>>> locale.getlocale()
(`es_ES`, `cp1252`)
#INCORRECT FORMAT, ADD A "." AT THE END
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
ene.
>>> locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8')
`es_ES.UTF-8`
#FORMATO INCORRECTO, AÑADE UN "." a may
>>> print (datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b'))
ene.
>>> print(datetime.strptime('18ene2021', '%d%b%Y'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\galonsoi\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Users\galonsoi\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data '18ene2021' does not match format '%d%b%Y'
>>> print(datetime.strptime('18ene.2021', '%d%b%Y'))
2021-01-18 00:00:00 ----> THIS IS OK BECAUSE I WROTE THE DOT AT THE END OF THE ABBREVIATED MONTH
You could make use of dateutil's parser, where you can set custom month names via the parser.parserinfo class. Ex:
import locale
locale.setlocale(locale.LC_ALL, 'Spanish_Spain.1252') # set locale for reproducibility
import calendar
from dateutil import parser
# subclass parser.parserinfo and set custom month names with dots stripped:
class LocaleParserInfo(parser.parserinfo):
MONTHS = [(ma.strip('.'), ml) for ma, ml in zip(calendar.month_abbr, calendar.month_name)][1:]
s = '18ene2021'
print(parser.parse(s, parserinfo=LocaleParserInfo()))
# 2021-01-18 00:00:00

Converting the received data into binary form in python

I want to convert the received hex data into binary form. I get ValueError.
For example, I want the first value in the output to be printed as 0000.
received_data = " ".join("{:02x}".format(byte) for byte in (data))
print(received_data)
P_data = "{0:b}".format(received_data[0:1])
Output:
01 04 04
Error:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Try\test1\test2.py", line 22, in
<module>
P_data="{0:b}".format(received_data[0:1])
ValueError: Unknown format code 'b' for object of type 'str'
You should first convert your string into an integer
P_data = '{0:b}'.format(int(received_data[0:1], 16)).zfill(4)

From string to datetime with or without millisecond

I have a list of strings each of them represent a time with or without milliseconds, e.g.
l = ['03:18:45.2345', '03:19:23']
And I want to convert each string into a datetime object. Now I'm running:
>>> l = ['03:18:45.2345', '03:19:23']
>>> for item in l:
... print datetime.datetime.strptime(item, "%H:%M:%S.%f")
...
1900-01-01 03:18:45.234500
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '03:19:23' does not match format '%H:%M:%S.%f'
Hence, the question is: How do I iterate the list converting each element in a datetime object?
The first thought is to have a try..except..:
try:
print datetime.datetime.strptime(item, "%H:%M:%S.%f")
except:
print datetime.datetime.strptime(item, "%H:%M:%S")
Is there any way to do that without catching the ValueError?
l = ['03:18:45.2345', '03:19:23']
for item in l:
time_format = "%H:%M:%S.%f" if '.' in item else "%H:%M:%S"
print datetime.datetime.strptime(item, time_format)
If you are handling more complicated situation(the date string more complex). I recommend you to use dateutil instead of the datetime module.
dateutil.parser offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.
The prototype of this function is: parse(timestr)(you don't have to specify the format yourself).
DEMO
>>> parse("2003-09-25T10:49:41")
datetime.datetime(2003, 9, 25, 10, 49, 41)
>>> parse("2003-09-25T10:49")
datetime.datetime(2003, 9, 25, 10, 49)
Fuzzy parsing:
>>> s = "Today is 25 of September of 2003, exactly " \
... "at 10:49:41 with timezone -03:00."
>>> parse(s, fuzzy=True)
datetime.datetime(2003, 9, 25, 10, 49, 41,
tzinfo=tzoffset(None, -10800))
ValueError approach is fine but if you want to avoid try/except here:
#!/usr/bin/env python
from datetime import datetime
for time_string in ['03:18:45.2345', '03:19:23']:
time_string, dot, us = time_string.partition('.')
d = datetime.strptime(time_string, '%H:%M:%S')
if dot:
d = d.replace(microsecond=datetime.strptime(us, '%f').microsecond)
print(repr(d.time()))
Output
datetime.time(3, 18, 45, 234500)
datetime.time(3, 19, 23)

Issue using eval function on value in list

Here is my code. It is the last eval line that is returning a syntax error
def format_date():
month_abrv = ['Jan','Feb','Mar','Apr','May','Jun','Jul',
'Aug','Sep','Oct','Nov','Dec']
print('''This program takes an input in the format MM/DD/YYYY(ex:09/23/2014)
and outputs date in format DD Mth, YYYY (ex: 23 Sep, 2014)''')
date_string = input('\nInput date in format MM/DD/YYYY ')
date_list = date_string.split('/')
date_list[0] = eval(date_list[0])
format_date()
Here is the error
Traceback (most recent call last):
File "C:/Python34/Python ICS 140/FormatDate.py", line 16, in <module>
format_date()
File "C:/Python34/Python ICS 140/FormatDate.py", line 14, in format_date
date_list[0] = eval(date_list[0])
File "<string>", line 1
09
^
SyntaxError: invalid token
After doing a little more digging I found that Python interprets numbers starting with 0s as octal numbers. using the int() function to change '09' to 9 worked in this case.

python convert string "0" to float gives error

i have the following code in my python script, to launch an application and grab the output of it.
An example of this output would be 'confirmed : 0'
Now i only want to know the number, in this case zero, but normally this number is float, like 0.005464
When i run this code it tells me it cannot convert "0" to float. What am i doing wrong?
This is the error i get now:
ValueError: could not convert string to float: "0"
cmd = subprocess.Popen('/Applications/Electrum.app/Contents/MacOS/Electrum getbalance', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
if "confirmed" in line:
a,b=line.split(': ',1)
if float(b)>0:
print "Positive amount"
else:
print "Empty"
According to the exception you got, the value contained in b is not 0, but "0" (including the quotes), and therefore cannot be converted to a float directly. You'll need to remove the quotes first, e.g. with float(b.strip('"')).
As can be seen in the following examples, the exception description does not add the quotes, so they must have been part of the original string:
>>> float('"0"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: "0"
>>> float('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: a
I have tested the code and found that split(': ', 1) result contains string
>>> line = "1: 456: confirmed"
>>> "confirmed" in line
True
>>> a,b=line.split(': ', 1)
>>> a
'1'
>>> b
'456: confirmed'

Categories