How to convert datetime string with +00:00 to datetime - python

I'm trying to convert this string to a datetime object in Python. I don't understand the time part of the string '+00:00'. What does that mean and how do I format this string? '2021-01-04 04:00:00+00:00'
Thank you

From the documentation, that is the timezone indicator. +00:00 represents UTC.
The string format indicator for timezone is %z.
%z | UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

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 date string to Datetime Python Format Error

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.

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

How to convert a UTC datetime string into date?

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.

change date format in django

I'me trying to use this eventCalendar in Django, which saves and shows dates in this format:
2012-02-27T13:15:00.000+10:00
but when I save events in the database, they're saved in this format:
Mon Feb 27 2012 13:15:00 GMT+0330 (Iraq Standard Time)
so events from the database won't appear on the calendar because of this format. How can I convert this format?
I tried some thing like this:
datetime.strptime(mydatetime, "%Y-%m-%dT%H:%M:%S+0000")
but I'm repeatedly getting errors like this:
'module' object has no attribute 'strptime'
Edit:date is in string format
strptime is used to parse a string into a datetime object. The format string indicates how to parse the string, not the format you want the datetime to take when later printed as a string. So first off you need to make the format string match the date format of the input string.
Once you've gotten a datetime from strptime, you can then use strftime with your current format string to get it into the display you want.
That said, though, it appears you've got a problem with your imports. The error seems to indicate that you've done:
import datetime
datetime.strptime(...)
That's incorrect. strptime and strftime are methods off datetime.datetime, so you need to either modify your import like:
from datetime import datetime
Or, modify your call to strptime like:
datetime.datetime.strptime(...)
UPDATE
You're starting off with a string like Mon Feb 27 2012 13:15:00 GMT+0330 (Iraq Standard Time). Python is pretty awesome, but it's not omniscient; if you want to convert this to a datetime you have to tell it how. That's the purpose of the format string you pass to strptime. You need to create a format string that represents your current string date and time as represented in the database (exercise left to reader). Think in reverse, along the lines of it you wanted to actually represent a datetime like that, how would you do it.
This will net you a datetime. From there, you can now format that datetime as a string with strftime, passing the actual format you want, this time.
So the process is:
Create a format string representing your current string from the database
Use that format string as an argument to strptime to get a datetime
Create a format string representing the format you want the date to be in (already done)
Use that format string as the argument to strftime to convert the datetime from step 2 to your desired string.

Categories