This question already has answers here:
How to determine appropriate strftime format from a date string?
(4 answers)
Closed 5 years ago.
I'm getting a date as a string, then I'm parsing it to datetime object.
Is there any way to check what's is the date format of the object?
Let's say that this is the object that I'm creating:
modified_date = parser.parse("2015-09-01T12:34:15.601+03:00")
How can i print or get the exact date format of this object, i need this in order to verify that it's in the correct format, so I'll be able to to make a diff of today's date and the given date.
I had a look in the source code and, unfortunately, python-dateutil doesn't expose the format. In fact it doesn't even generate a guess for the format at all, it just goes ahead and parses - the code is like a big nested spaghetti of conditionals.
You could have a look at dateinfer which looks to be what you're searching for, but these are unrelated libraries so there is no guarantee at all that python-dateutil will parse with the same format that dateinfer suggests.
>>> from dateinfer import infer
>>> s = "2015-09-01T12:34:15.601+03:00"
>>> infer([s])
'%Y-%d-%mT%I:%M:%S.601+%m:%d'
Look at that .601. Close but not cigar. I think it has probably also mixed up the month and the day. You might get better results by giving it more than one date string to base the guess upon.
i need this in order to verify that it's in the correct format
If you know the expected time format (or a set of valid time formats) then you could just parse the input using it: if it succeeds then the time format is valid (the usual EAFP approach in Python):
for date_format in valid_date_formats:
try:
return datetime.strptime(date_string, date_format), date_format
except ValueError: # wrong date format
pass # try the next format
raise ValueError("{date_string} is not in the correct format. "
"valid formats: {valid_date_formats}".format(**vars()))
Here's a complete code example (in Russian -- ignore the text, look at the code).
If there are many valid date formats then to improve time performance you might want to combine them into a single regular expression or convert the regex to a deterministic or non-deterministic finite-state automaton (DFA or NFA).
In general, if you need to extract dates from a larger text that is too varied to create parsing rules manually; consider machine learning solutions e.g., a NER system such as webstruct (for html input).
Related
I am trying to convert a string with "2019-01-06T01:00:24.908821" to a date using the "datetime.strptime" function. However, I am not able to find the format for this conversion to be successful.
I'm using the entries as proposed by the library itself, however I'm getting a "ValueError" when I try to perform the conversion.
ValueError: time data '2019-01-06T01:00:24.908821' does not match format '%Y-%m-%dT%H:%M:%S:%f'
If you would like to read the proposed standards, you can find here:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
My code:
from datetime import datetime
datetime.strptime("2019-01-06T01:00:24.908821", "%Y-%m-%dT%H:%M:%S:%f")
You have a colon (:) instead of a decimal (.) before the %f in your format string.
Change
datetime.strptime("2019-01-06T01:00:24.908821", "%Y-%m-%dT%H:%M:%S:%f")
To
datetime.strptime("2019-01-06T01:00:24.908821", "%Y-%m-%dT%H:%M:%S.%f")
I'm trying to validate a string that's supposed to contain a timestamp in the format of ISO 8601 (commonly used in JSON).
Python's strptime seems to be very forgiving when it comes to validating zero-padding, see code example below (note that the hour is missing a leading zero):
>>> import datetime
>>> s = '1985-08-23T3:00:00.000'
>>> datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime(1985, 8, 23, 3, 0)
It gracefully accepts a string that's not zero-padded for the hour for example, and doesn't throw a ValueError exception as I would expect.
Is there any way to enforce strptime to validate that it's zero-padded? Or is there any other built-in function in the standard libs of Python that does?
I would like to avoid writing my own regexp for this.
There is already an answer that parsing ISO8601 or RFC3339 date/time with Python strptime() is impossible: How to parse an ISO 8601-formatted date?
So, to answer you question, no there is no way in the standard Python library to reliable parse such a date.
Regarding the regex suggestions, a date string like
2020-14-32T45:33:44.123
would result in a valid date. There are lots of Python modules (if you search for "iso8601" on https://pypi.python.org), but building a complete ISO8601 Validator would require things like leap seconds, the list of possible time zone offset values and many more.
To enforce strptime to validate leading zeros for you you'll have to add your own literals to Python's _strptime._TimeRE_cache. The solution is very hacky, most likely not very portable, and requires writing a RegEx - although only for the hour part of a timestamp.
Another solution to the problem would be to write your own function that uses strptime and also converts the parsed date back to a string and compares the two strings. This solution is portable, but it lacks for the clear error messages - you won't be able to distinguish between missing leading zeros in hours, minutes, seconds.
You said you want to avoid a regex, but this is actually the type of problem where a regex is appropriate. As you discovered, strptime is very flexible about the input it will accept. However, the regex for this problem is relatively easy to compose:
import re
date_pattern = re.compile(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}')
s_list = [
'1985-08-23T3:00:00.000',
'1985-08-23T03:00:00.000'
]
for s in s_list:
if date_pattern.match(s):
print "%s is valid" % s
else:
print "%s is invalid" % s
Output
1985-08-23T3:00:00.000 is invalid
1985-08-23T03:00:00.000 is valid
Try it on repl.it
The only thing I can think of outside of messing with Python internals is to test for the validity of the format by knowing what you are looking for.
So, if I garner it right, the format is '%Y-%m-%dT%H:%M:%S.%f' and should be zero padded.
Then, you know the exact length of the string you are looking for and reproduce the intended result..
import datetime
s = '1985-08-23T3:00:00.000'
stripped = datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
try:
assert len(s) == 23
except AssertionError:
raise ValueError("time data '{}' does not match format '%Y-%m-%dT%H:%M:%S.%f".format(s))
else:
print(stripped) #just for good measure
>>ValueError: time data '1985-08-23T3:00:00.000' does not match format '%Y-%m-%dT%H:%M:%S.%f
This question already has answers here:
Python 2.7 how parse a date with format 2014-05-01 18:10:38-04:00 [duplicate]
(2 answers)
Closed 6 years ago.
I am receiving a json that prints time data '2016-04-15T02:19:17+00:00' I I cant seem to figure out the format of this unicode string.
I need to find a difference in time between then and now. The first step in that is to convert the string to structured format and Iam not able to find the format
fmt='"%Y-%m-%d %H:%M:%S %Z'
#fmt='%Y-%m-%d %H:%M:%S.%f'
print datetime.datetime.strptime(result_json['alert_time'], fmt)
I keep getting exception that it is not the same format
time data '2016-04-15T02:19:17+00:00' does not match format '"%Y-%m-%d %H:%M:%S %Z'
There are a few problems with your format. First, it has a double quote " in it. Second, you need to include the T between the date and the time. Third, the timezone offset is not standard. Here is code that will work:
print datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')
If your alert_time is always in GMT, you can just trim the timezone off before calling strptime.
The answer by Brent is the safer and faster option rather than having things going on under the hood. But the amount of times I've had datetime as a frustrating bottleneck not associated with the main problem I wanted to test out, I will also point out that dateparser here has not yet been wrong for me and will take a huge range of inputs.
import dateparser
import datetime
date = '2016-04-15T02:19:17+00:00'
date_parser_format = dateparser.parse(date)
datetime_format = datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')
print date_parser_format
print datetime_format
So for example I am given Strings such as:
1/2/12 or
12/03/14 or
7/3/2015 or
07/05/05.
Note: I do not know what format the string will be in because the dates are being collected from excel files. How can I format it to yyyy/dd/mm or similar to 2000/09/03
The other post about this subject do not accommodate everything I'm looking for
The dateutil library works pretty well
I have a date string like "2011-11-06 14:00:00+00:00". Is there a way to check if this is in UTC format or not ?. I tried to convert the above string to a datetime object using utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z) so that i can compare it with pytz.utc, but i get 'ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M%S+%z'
How to check if the date string is in UTC ?. Some example would be really appreciated.
Thank You
A simple regular expression will do:
>>> import re
>>> RE = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$')
>>> bool(RE.search('2011-11-06 14:00:00+00:00'))
True
By 'in UTC format' do you actually mean ISO-8601?. This is a pretty common question.
The problem with your format string is that strptime just passes the job of parsing time strings on to c's strptime, and different flavors of c accept different directives. In your case (and mine, it seems), the %z directive is not accepted.
There's some ambiguity in the doc pages about this. The datetime.datetime.strptime docs point to the format specification for time.strptime which doesn't contain a lower-case %z directive, and indicates that
Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C.
But then it also points here which does contain a lower-case %z, but reiterates that
The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common.
There's also a bug report about this issue.