How can I convert: u'2012-11-07T13:25:10.703Z' to Python datetime?
EDIT
I intend to use something like this:
>>> from datetime import datetime
>>> datetime.strptime('2011-03-07','%Y-%m-%d')
datetime.datetime(2011, 3, 7, 0, 0)
but how can I change the second argument to accommodate my date format?
Use datetime.datetime.strptime:
datetime.datetime.strptime(u'2012-11-07T13:25:10.703Z', '%Y-%m-%dT%H:%M:%S.%fZ')
Result:
datetime.datetime(2012, 11, 7, 13, 25, 10, 703000)
See the description of the strptime behaviour.
Use strptime from the datetime module
import datetime
datetime.strptime(u'2012-11-07T13:25:10.703Z', '%Y-%m-%dT%H:%M:%S.%fZ')
>>> datetime.datetime(2012, 11, 7, 13, 25, 10, 703000)
Related
In Python I would like to turn my str to time object and I am receiving an error.
ValueError: time data '2022-04-13T09:52:49-04:00' does not match format
What format should I use here?
Thanks
Try:
>>> datetime.strptime('2022-04-13T09:52:49-04:00',"%Y-%m-%dT%H:%M:%S%z")
datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
ISO 8601 format was used, so it is task for datetime.datetime.fromisoformat
import datetime
d = '2022-04-13T09:52:49-04:00'
dt = datetime.datetime.fromisoformat(d)
print(repr(dt))
output
datetime.datetime(2022, 4, 13, 9, 52, 49, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
Problem: I have the following string '2021-03-10T09:58:17.027323+00:00' which I want to convert to datetime. I have difficulties with the format. This is what I tried so far:
datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.z")
Any help is highly appreciated!
The correct format string is "%Y-%m-%dT%H:%M:%S.%f%z"
>>> from datetime import datetime
>>> datetime.strptime('2021-03-10T09:58:17.027323+00:00', "%Y-%m-%dT%H:%M:%S.%f%z")
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2021-03-10T09:58:17.027323+00:00')
datetime.datetime(2021, 3, 10, 9, 58, 17, 27323, tzinfo=datetime.timezone.utc)
But as mentioned in the comments - better use fromisoformat()
Given that your string is known from before and you won't be using a now time feature, you can check here I think you can use the following code:
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
I have time = '2020-06-24T13:30:00-04:00'. How can I change it to a dateTime object in UTC time. I would prefer not to use pd.Timestamp(time).tz_convert("UTC").to_pydatetime() because it returns a weird output that would look like this datetime.datetime(2020, 6, 24, 17, 30, tzinfo=<UTC>). As a result, when I check for equality with datetime.datetime(2020, 6, 24, 17, 30), it return False.
Edit:
import datetime
import pytz
time = '2020-06-24T13:30:00-04:00
dt = datetime.datetime(2020, 6, 24, 17, 30)
print("dt: ",dt)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z').astimezone(pytz.utc)
print("so:",so)
print(dt == so)
outputs
dt: 2020-06-24 17:30:00
so: 2020-06-24 17:30:00+00:00
False
How can I get it to properly evaluate to True?
#1 Since your string is ISO 8601 compatible, use fromisoformat() on Python 3.7+:
from datetime import datetime, timezone
s = '2020-06-24T13:30:00-04:00'
dtobj = datetime.fromisoformat(s)
# dtobj
# datetime.datetime(2020, 6, 24, 13, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
Note that this will give you a timezone-aware datetime object; the tzinfo property is a UTC offset. You can easily convert that to UTC using astimezone():
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#2 You can achieve the same with strptime (also Python3.7+ according to this):
dtobj = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#3 If you want to turn the result into a naive datetime object, i.e. remove the tzinfo property, replace with None:
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
#4 For older Python versions, you should be able to use dateutil's parser:
from dateutil import parser
dtobj = parser.parse(s)
dtobj_utc = dtobj.astimezone(timezone.utc)
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
Alright so my previous answer was sort of wack because I did not understand your issue entirely so I am rewriting it. You problem is that you are constructing a datetime object from a string and it is timezone aware(UTC). However, whenever you make a datetime object in python, dt = datetime.datetime(2020, 6, 24, 17, 30), it is creating it but with no timezone information (which you can check using .tzinfo on it). All you would need to do is make dt timezone aware when you first create it. See below my code snippit.
import datetime
time = '2020-06-24T13:30:00-04:00'
dt = datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
print("dt: ",dt.tzinfo)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z')
print("so:",so.tzinfo)
print(dt == so)
How can I change a timezone in a datetimefield.
right now I have
datetime.datetime(2013, 7, 16, 4, 30, tzinfo=<UTC>)
how can modify the tzinfo just for display not to update on the db.
Use pytz for such things.
From the pytz docs, you can use astimezone() to transform time into different time zone, as example below.
>>> eastern = timezone('US/Eastern')
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST-0500'
I have a system (developed in Python) that accepts datetime as string in VARIOUS formats and i have to parse them..Currently datetime string formats are :
Fri Sep 25 18:09:49 -0500 2009
2008-06-29T00:42:18.000Z
2011-07-16T21:46:39Z
1294989360
Now i want a generic parser that can convert any of these datetime formats in appropriate datetime object...
Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!
As #TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:
>>> from dateutil.parser import parse
>>> parse("Fri Sep 25 18:09:49 -0500 2009")
datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))
>>> parse("2008-06-29T00:42:18.000Z")
datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())
>>> parse("2011-07-16T21:46:39Z")
datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())
The unixtime format it seems to hiccough on, but luckily the standard datetime.datetime is up for the task:
>>> from datetime import datetime
>>> datetime.utcfromtimestamp(float("1294989360"))
datetime.datetime(2011, 1, 14, 7, 16)
It is rather easy to make a function out of this that handles all 4 formats:
from dateutil.parser import parse
from datetime import datetime
def parse_time(s):
try:
ret = parse(s)
except ValueError:
ret = datetime.utcfromtimestamp(s)
return ret
You should look into the dateutil package.