How do I find the date format ? [duplicate] - python

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

Related

Convert a timezone aware string to datetime python which is in format like '2012-11-01T04:16:13.000Z' [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 1 year ago.
I have stumbled upon a coding question where I have to convert a timezone-aware string like 2021-11-01T02:08:13.000Z to a Python datetime object.
I have seen many examples where timezone aware string is like in the format 2012-11-01T04:16:13-04:00, but for me as you can see the string is little different with the ".000Z" at the end.
I tried the below code:
from datetime import datetime
format = '%Y-%m-%dT%H:%M:%S%z'
time='2012-11-01T04:16:13.000Z'
date_time_obj = datetime.strptime(time, format)
print ("date",date_time_obj)
But I'm getting the error:
ValueError: time data '2012-11-01T04:16:13.000Z' does not match format '%Y-%m-%dT%H:%M:%S%z'
also tried doing like this:
from datetime import datetime
time='2012-11-01T04:16:13.000Z'
date_time_obj = datetime.fromisoformat(time)
But I'm getting this error:
Errpr: Invalid ISO format string:
I gone through many pages but was unable to find that particular format and how to convert it to a datetime aware string. Can anyone please help.
You can do all of this using 'dateutil.parser.isoparse'. No need to strip out information (dropping the milliseconds), no need to fuss with the formatting string.
from dateutil import parser
time='2012-11-01T04:16:13.000Z'
date_time_obj = parser.isoparse(time)
print ("date",date_time_obj)
> date 2012-11-01 04:16:13+00:00
You may change your format like this:
format = '%Y-%m-%d %H:%M:%S'
And convert time like you format by doing this:
time='2012-11-01T04:16:13.000Z'
time=time.replace("T"," ").split(".")[0]
Or you may format it like
format = '%Y-%m-%dT%H:%M:%S.%f'
And you don't have to do anything for time now.
time='2012-11-01T04:16:13.000Z'

Convert string object to date object in Python [duplicate]

This question already has answers here:
Convert string into Date type on Python [duplicate]
(5 answers)
Closed 2 years ago.
I have a string object
value="2020-02-28"
and want output as a date object in python.
Used
datetime_value= datetime.strptime((str(value), "%b%d, %Y"))
But it does not work.
Make these minor changes :
from _datetime import datetime
value="2020-02-28"
datetime_value= datetime.strptime(value, "%Y-%m-%d")
print(datetime_value, type(datetime_value))
# 2020-02-28 00:00:00 <class 'datetime.datetime'>
First, "it does not work" is really not helpful in any way, shape or form. When you request help, providing the actual feedback you get (e.g. error message, traceback, ...) is significantly more actionable than providing... nothing.
Second, the format string passed to strptime (second parameter) is supposed to match the actual date, that means the placeholders should parse the fields you're trying to match, and the not-placeholders should match the not-fields.
Here your date is {year}-{month}-{day-of-month}, but the format string %b%d, %Y stands for {Month as locale’s abbreviated name}{Day of the month}, {Year}. None of the separators, fields or order match.
What you want is %Y-%m-%d.
Third, value is a string, why are you converting it to a string again?

Unable to parse the strptime in python

I am converting the datetime into time. My JSON datetime format is "2017-01-02T19:00:07.9181202Z". I have placed my code below:
from datetime import datetime
date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z', '%Y-%m-%dT%H:%M:%S.%fZ')
time = date_format.strftime("%I:%M %p")
print(time)
Error message as below:
After that I read this python date-time document. It says that microsecond digit should be 6. But, JSON date-time microsecond has 7 digit.
Message from Python document:
%f is an extension to the set of format characters in the C standard
(but implemented separately in datetime objects, and therefore always
available). When used with the strptime() method, the %f directive
accepts from one to six digits and zero pads on the right.
I need result like 07:00 PM format. Is there any alternative method?
Thanks in advance.
If you're sure that the input will always be like that, you can just remove the extra digit before passing that string to strptime:
date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z'[:-2] + 'Z', '%Y-%m-%dT%H:%M:%S.%fZ')
This is dirty, but gives the idea - remove the last two characters (the extra digit and "Z"), re-add the "Z".

Converting Iso8601 with non-decimal UTC zone offest [duplicate]

This question already has answers here:
How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]
(11 answers)
Closed 7 years ago.
How do I modify the code below to handle a timezone, note there is no decimal.
2015-12-22T11:57:11-08:00, -8:00 is causing me issues, does epoch time take time zone into account?
timegm(datetime.strptime(datestring, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
There are a few issues here.
If your time doesn't include a microsecond block, this date string will not work with the format string you provided. Just try it without the -08:00 bit. That means you either need to assume that all your times won't have that block or you need to account for both possibilities.
strptime does a TERRIBLE job of dealing with ISO8601 offsets. If you look at the formatting guide, you'll notice that you can use %z for +/-HHMM, but ISO8601 time zones (in my experience) are almost always presented with the format +/-HH:MM. And even then %z has a nasty habit of being called a bad directive in the format string.
To answer your question, yes, time zone matters. The UNIX epoch is seconds since 1970-01-01T00:00:00+00:00. More importantly, even if you correctly assign the datetime object's tzinfo when you parse the string, timetuple will NOT take into account that tzinfo. You need to use utctimetuple
So now you just need to properly parse the datetime. There are solutions that don't use external libraries, but I find the easiest way to parse ISO8601 date strings is to use the python-dateutil package available via pip:
>>> import calendar
>>> from dateutil import parser
>>> datestring = '2015-12-22T11:57:11-08:00'
>>> tz_aware_datetime = parser.parse(datestring)
>>> tz_aware_datetime
datetime.datetime(2015, 12, 22, 11, 57, 11, tzinfo=tzoffset(None, -28800))
>>> calendar.timegm(tz_aware_datetime.utctimetuple())
1450814231

Python - Getting the date format [duplicate]

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).

Categories