string datetime format to time() unix time format in python - python

I know this must be a well covered question elsewhere, but most questions I saw on SO looked like they were going in the opposite direction. I understand how to convert FROM time.time() TO human-readable datetime format as follows:
>>> import time, datetime
>>> thetime = time.time()
>>> thetime
1375289544.41976
>>> datetime.datetime.fromtimestamp(thetime).strftime("%Y-%m-%d %H:%M:%S")
'2013-07-31 12:51:08'
What's the function for going the inverse direction?
>>> thetime = '2013-07-30 21:23:14.744643'
>>> time.strptime(thetime, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: .744643
I'd like to go from the string to the seconds since the epoch format.
UPDATE
This is what I'm using, but it seems inelegant---there must be a function that does this already, right?
def datetostamp(x):
thetime = x.split('.')
return(time.mktime(time.strptime(thetime[0], "%Y-%m-%d %H:%M:%S")) + float('.'+thetime[1]))
>>> thetime = '2013-07-30 21:23:14.744643'
>>> datetostamp(thetime)
1375233794.744643
UPDATE 2
Maybe more simply, I'm just missing the format code for fractions of seconds?

You were missing the format for fractions of a second.
time.strptime(thetime, "%Y-%m-%d %H:%M:%S.%f")

Related

ValueError: Unknown string format in Python?

I'm trying to parse a basic iso formatted datetime string in Python, but I'm having a hard time doing that. Consider the following example:
>>> import json
>>> from datetime import datetime, date
>>> import dateutil.parser
>>> date_handler = lambda obj: obj.isoformat()
>>> the_date = json.dumps(datetime.now(), default=date_handler)
>>> print the_date
"2017-02-18T22:14:09.915727"
>>> print dateutil.parser.parse(the_date)
Traceback (most recent call last):
File "<input>", line 1, in <module>
print dateutil.parser.parse(the_date)
File "/usr/local/lib/python2.7/site-packages/dateutil/parser.py", line 1168, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/usr/local/lib/python2.7/site-packages/dateutil/parser.py", line 559, in parse
raise ValueError("Unknown string format")
ValueError: Unknown string format
I've also tried parsing this using the regular strptime:
>>> print datetime.strptime(the_date, '%Y-%m-%dT%H:%M:%S')
# removed rest of the error output
ValueError: time data '"2017-02-18T22:11:58.125703"' does not match format '%Y-%m-%dT%H:%M:%S'
>>> print datetime.strptime(the_date, '%Y-%m-%dT%H:%M:%S.%f')
# removed rest of the error output
ValueError: time data '"2017-02-18T22:11:58.125703"' does not match format '%Y-%m-%dT%H:%M:%S.%f'
Does anybody know how on earth I can parse this fairly simple datetime format?
note the error message:
ValueError: time data '"2017-02-18T22:11:58.125703"'
There are single quotes + double quotes which means that the string actually contains double quotes. That's because json serialization adds double quotes to strings.
you may want to strip the quotes around your string:
datetime.strptime(the_date.strip('"'), '%Y-%m-%dT%H:%M:%S.%f')
or, maybe less "hacky", de-serialize using json.loads:
datetime.strptime(json.loads(the_date), '%Y-%m-%dT%H:%M:%S.%f')

Python - strptime ValueError: time data does not match format '%Y/%m/%d'

I believe I am missing something trivial. After reading all the questions about strptime ValueError yet I feel the format seems right, Here is the below error I get
Traceback (most recent call last):
File "loadScrip.py", line 18, in <module>
nextDate = datetime.datetime.strptime(date, "%Y/%m/%d")
File "/usr/lib64/python2.6/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
I am using Python 2.6.6 under Linux x86_64. Any help will be much appreciated.
Your error indicates you have data with the letter l (lowercase L) instead of the number 1 in the year:
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
That is not a valid date that'll fit the requested format; replacing the l with 1 and the input date works just fine:
>>> import datetime
>>> datetime.datetime.strptime('20l2/08/25', "%Y/%m/%d")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '20l2/08/25' does not match format '%Y/%m/%d'
>>> datetime.datetime.strptime('2012/08/25', "%Y/%m/%d")
datetime.datetime(2012, 8, 25, 0, 0)
Fix your input, the format is correct.
Here's how to do it with the string variable:
>>> start_day = 2015188
>>> print start_day
2015188
>>> print conv
time.struct_time(tm_year=2015, tm_mon=7, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=188, tm_isdst=-1)
>>> conv = time.strptime( str(start_day), "%Y%j" )
>>> print conv
time.struct_time(tm_year=2015, tm_mon=7, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=188, tm_isdst=-1)
For whatever reason, you have to put the string variable inside the str() thing and all the examples I have found online only show the date in quotes.

How do you check a python string to see if it's in HH:MM time format?

what is a regex for matching the HH:MM time format in python?
I was using
def is_time(self, str):
reg = re.compile(r'[1-9]|1[0-2]:[0-9]{2}')
if re.match(reg, str):
return True
else:
return False
I've also tried :
reg = re.compile(r'^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')
but i keep getting
TypeError: %d format: a number is required, not str
it makes sense that I'm getting that error because I'm checking numbers in strings, but I'm not sure how to fix it. any help would be greatly appreciated.
You should probably use datetime.strptime
>>> import datetime
>>> datetime.datetime.strptime('12:34', '%H:%M')
datetime.datetime(1900, 1, 1, 12, 34)
>>> datetime.datetime.strptime('99:99', '%H:%M')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '99:99' does not match format '%H:%M'
You should use just:
if reg.search(strs)
or simply:
return reg.search(strs).

Python date parsing from Amazon EC2 EBS

I'm having an issue trying to parse a date that's being returned by an EC2 script that checks the last backup of a volume.
I'm getting the current string format returned as a string and I want to parse it into a datetime object but because of the extra characters in the returned string, datetime.strptime does not work properly. Is there a way to get the string into a datetime object without having to use dateutils as I'm having issues with that as well.
This is the date string being returned:
2013-06-26T02:01:05.000Z
This is my code trying to parse it:
startTime = datetime.strptime(s.start_time, '%Y-%m-%dT%H:&M:%S.%fZ')
Obviously this isn't working as when I try and print startTime it does nothing.
I think it's a typo, instead of % you used &.
'%Y-%m-%dT%H:&M:%S.%fZ'
^
|
this is wrong
Demo:
>>> strs = "2013-06-26T02:01:05.000Z"
>>> datetime.strptime(strs, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2013, 6, 26, 2, 1, 5)
You have an error in your format; it's not &M but %M:
datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%fZ')
The corrected format works just fine:
>>> t = '2013-06-26T02:01:05.000Z'
>>> from datetime import datetime
>>> datetime.strptime(t, '%Y-%m-%dT%H:&M:%S.%fZ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2013-06-26T02:01:05.000Z' does not match format '%Y-%m-%dT%H:&M:%S.%fZ'
>>> datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2013, 6, 26, 2, 1, 5)

How to decide if an string is in hh:mm format in python?

I'd like to know if there is a function which returns True if a string is in "hh:mm" hour format?
I can write my own function, but it would be good if there is a standard function.
Best Regards
Just try to interpret it using the time module, and catch the ValueError raised when the conversion fails:
>>> time.strptime('08:30', '%H:%M')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>> time.strptime('08:70', '%H:%M')
Traceback (most recent call last):
(...)
ValueError: unconverted data remains: 0
>>> time.strptime('0830', '%H:%M')
Traceback (most recent call last):
(...)
ValueError: time data '0830' does not match format '%H:%M'
The only thing this doesn't check is that you actually specify the correct number of digits. Checking if len(time_string) == 5 might be simple enough to check that.
Edit: inspired by Kimvais in the comments; to wrap it as a function:
def is_hh_mm_time(time_string):
try:
time.strptime(time_string, '%H:%M')
except ValueError:
return False
return len(time_string) == 5
You can use time.strptime:
>>> help(time.strptime)
Help on built-in function strptime in module time:
strptime(...)
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as strftime()).
To parse a time string that works:
>>> time.strptime('12:32', '%H:%M')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=32, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
If you pass in a time string that is not valid, you will get an error:
>>> time.strptime('32:32', '%H:%M')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\lib\_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '32:32' does not match format '%H:%M'
So... your function could look like this:
def is_hh_mm(t):
try:
time.strptime(t, '%H:%M')
except:
return False
else:
return True

Categories

Resources