There is a datetime string that I would like to convert back into a date. The time zone is giving me trouble and I don't know how to solve it.
datetime.datetime.strptime(json_event['date_time'], '%a, %d %b %Y %H:%M:%S %Z')
I get the error message:
ValueError: time data 'Tue, 08 Apr 2014 17:57:34 -0000' does not match
format '%a, %d %b %Y %H:%M:%S %Z'
If I leave %Z out, I get this error message:
ValueError: unconverted data remains: -0000
The date is originally a UTC:
current_date = datetime.datetime.utcnow()
UPDATE:
I would like to solve this natively without any external libraries such as dateutil.parser, hence the solution in the duplicate doesn't help me.
import dateutil.parser
date = dateutil.parser.parse(json_event['date_time'])
If you don't have dateutil, get it.
pip install python-dateutil
If you are always getting UTC times: Ignore the last 6 chars (space, sign, 4 digts) and then convert to datetime as you've done without the %Z.
One issue you'll have is that your system will assume that it is your local timezone and if you convert it to any other timezone, it will convert wrongly. In that case, next step is to use this answer from another question.
If you get non-UTC times as well:
crop out the last 6 chars.
Do the strptime on the last 4 digits, with the format HHMM (%H%M) --> Y
Get the sign and reverse in step 5 below.
Then get the rest of the datetime as you have above (leaving those last 6 chars and no %Z in the format) --> X
Then X-Y (or X+Y, invert what is got from step 3) will give you a datetime object. Then follow the steps in the linked answer to make the datetime obj timezone aware.
Related
I know there are a lot of answers to this question online, but none of them have worked for me. I am trying to convert a date string into a Datetime object, of the following format: yyyy-mm-dd
My date_string is '2017-02-02T00:00:00Z'
I am trying to convert it by doing date_value = datetime.datetime.strptime(date_string, '%Y%m%d') but I'm getting the following error:
ValueError: time data '"2017-02-02T00:00:00Z"' does not match format
'%Y%m%d'
Also, should I be worried about the double quotes around my date_string string?
The second argument in the method strptime is the pattern of your string.
Here is the full list of available code formats. https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
All the remaining "non-informative" characters in your string can simply be put as-is in there correct places.
Thanks to #MrFuppes for this info: you should also parse the trailing "Z" as %z. This will signal python that it's a UTC datetime and not a local datetime.
Your code should be :
date_string = '2017-02-02T00:00:00Z'
date_value = datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')
As for the extra quotes, that's not wanted. You should try this beforehand :
date_string = date_string.strip("'").strip('"')
If strip() didn't work, you can call eval instead (usually not recommended) :
date_string = eval(date_string)
The solution is to parse your date_string first, and that should help. Using strptime() right away on an unparsed datetime string can sometimes cause problems. Also you shouldn't worry about your double quotes, it's fine.
First, install the python-dateutil library if you haven't already (pip install python-dateutil at the command line). Then test the solution with the following code.
import datetime
import dateutil.parser
date_string = '2017-02-02T00:00:00Z'
#we parse the string, it becomes a datetime object
parsed_date_string = dateutil.parser.parse(date_string)
print(parsed_date_string)
#output looks like this: 2017-02-02 00:00:00+00:00
#now your statement will work
date_value = datetime.datetime.strptime(str(parsed_date_string), '%Y-%m-%d %H:%M:%S%z')
print(date_value)
#output will also be: 2017-02-02 00:00:00+00:00
The strptime() statement worked this time because we parsed our date first with parse(). Note also that to use strptime() we need to cast our parsed_date_string back to a string because parse() converts our original string to an object of class datetime.datetime and strptime() is expecting a string.
Hopefully that helped.
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
How would I convert a date in string format to compare it with the current time?
I tried this:
import time, datetime
if time.strptime(date.find(text=True), "%a, %d/%m/%Y").now() > datetime.now():
But I get this error:
ValueError: time data u'Dom, 07/02/2016' does not match format '%a, %d/%m/%Y'
Need advice on how to do this.
You need to setup the proper locale before handling language/region specific data.
Try again with
import locale
locale.setlocale(locale.LC_TIME, '')
time.strptime(date_string, "%a, %d/%m/%Y")
The '' tells the library to pickup the current locale of your system (if one is set).
If you need to parse the date in a different locale, the situation is a little bit more complex. See How do I strftime a date object in a different locale? for the gritty details.
It is possible to explicitly set a specific locale, e.g.
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
time.strptime('Dom, 01/02/1903', '%a, %d/%m/%Y')
=> time.struct_time(tm_year=1903, tm_mon=2, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=32, tm_isdst=-1)
but remember, that this setting is global. strptime() does not accept a parameter to specify a particular locale to parse with, it always picks up the global locale.
If the date is user-supplied, I have used dateparser package as a welcome alternative. Especially so, since its parse() function accepts an explicit languages parameter.
I have a time String like this:
07/01/2015-14:31:58.520
I use this command line to convert it:
import time
timeStr = "07/01/2015-14:31:58.520"
time.strptime(timeStr,'%d/%m/%y-%H:%M:%S.%f')
But this returns:
ValueError: time data '07/01/2015-14:31:58.520' does not match format
'%d/%m/%y-%H:%M:S.%f'
My python version is 2.7.7
%y denotes a 2 digit year, but your string has a 4 digit year. Use %Y (capital Y) to denote a 4 digit year. See the docs for more information.
time.strptime(timeStr, '%d/%m/%Y-%H:%M:%S.%f')
Note that datetime.strptime may be more useful, as it will return a full datetime object rather than a tuple. The format syntax is essentially the same.
It should have been capital Y for year (%Y in place of %y)
time.strptime(timeStr,'%d/%m/%Y-%H:%M:%S.%f')
You need to use %Y instead of %y
time.strptime(timeStr,'%d/%m/%Y-%H:%M:%S.%f')
To get a datetime object, use python-dateutil
To install
pip install python-dateutil
Then
t = "07/01/2015-14:31:58.520"
from dateutil import parser
>>>parser.parse(t)
datetime.datetime(2015, 7, 1, 14, 31, 58, 520000)
tim = parser.parse(t)
>>>str(tim.date())
'2015-07-01'
All operations to datetime objects is possible.
the time.strptime syntax %d/%m/%y-%H:%M:%S.%f is incorrect, it should be
"%d/%m/%Y-%H:%M:%S.%f"
where the only difference is that %y has become %Y. The reason is because from the docs %y is without century number ( [00,99] ), whereas %Y is with century number, which is the syntax you use with "2015"
Tested and functinal in python 2.7.5 and 3.4.1
Edit: Zero answers when I started typing this, 6 answers by time of post, sorry about that!
Edit #2: datetime.strptime functions similarly, so if you want to use that as well, you can!
In Python, how can I convert a string like this:
Thu, 16 Dec 2010 12:14:05 +0000
to ISO 8601 format, while keeping the timezone?
Please note that the orginal date is string, and the output should be string too, not datetime or something like that.
I have no problem to use third parties libraries, though.
Using dateutil:
import dateutil.parser as parser
text = 'Thu, 16 Dec 2010 12:14:05 +0000'
date = parser.parse(text)
print(date.isoformat())
# 2010-12-16T12:14:05+00:00
Python inbuilt datetime package has build in method to convert a datetime object to isoformat. Here is a example:
>>>from datetime import datetime
>>>date = datetime.strptime('Thu, 16 Dec 2010 12:14:05', '%a, %d %b %Y %H:%M:%S')
>>>date.isoformat()
output is
'2010-12-16T12:14:05'
I wrote this answer primarily for people, who work in UTC and doesn't need to worry about time-zones. You can strip off last 6 characters to get that string.
Python 2 doesn't have very good internal library support for timezones, for more details and solution you can refer to this answer on stackoverflow, which mentions usage of 3rd party libraries similar to accepted answer.