Convert string to datetime python with milli-seconds - python

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)

Related

Date format for year/month/date'T'/hour/minute/second/timezone in Python

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

Changing string to UTC to dateTime object

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)

Custom date format parsing in python

I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value
You may try this way :
from datetime import datetime
date_str = '2016-04-15T12:24:20.707Z'
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(date)
Output:
2016-04-15 12:24:20.707000
You have to specify the format as "%Y-%m-%dT%H:%M:%S.%fZ" while conversion
In [11]: from datetime import datetime
In [12]: out_format = "%Y-%m-%d"
In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ"
In [14]: date_time_obj = datetime.strptime(time,input_format)
In [15]: date_time_obj
Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000)
In [16]: date_time_str = date_time_obj.strftime(out_format)
In [17]: date_time_str
Out[17]: '2016-04-15'
import dateutil.parser
from datetime import datetime
dt = dateutil.parser.parse('2016-04-15T12:24:20.707Z')
This seems to be working alright:
import dateparser
dateparser.parse('2016-04-15T12:24:20.707Z')
> datetime.datetime(2016, 4, 15, 12, 24, 20, 707000, tzinfo=<StaticTzInfo 'Z'>)
Probably iso8601 package is what you need
You may try this way if you need something on the fly:
This returns the current datetime in UTC, as a datetime object then immediately converts it to your preferred custom format.
from datetime import datetime, timezone
from time import strftime
# Get UTC Time datetime object and convert it to your preferred format.
print(f"Regular : { datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') }") # Regular : 2022-06-04 23:08:27
print(f"Log Format: { datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') }") # Log Format: 20220604_230827
print(f"YMD Format: { datetime.now(timezone.utc).strftime('%Y-%m-%d') }") # YMD Format: 2022-06-04
print(f"Time Format: { datetime.now(timezone.utc).strftime('%H:%M:%S') }") # Time Format: 23:08:27
# Without the f'String'
print(datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) # Regular : 2022-06-04 23:08:27
print(datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')) # Log Format: 20220604_230827
print(datetime.now(timezone.utc).strftime('%Y-%m-%d')) # YMD Format: 2022-06-04
print(datetime.now(timezone.utc).strftime('%H%M%S')) # Time Format: 23:08:27
# Details:
# Get current DateTime in UTC
datetime.now(timezone.utc)
# datetime.datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=datetime.timezone.utc)
type(datetime.now(timezone.utc))
# <class 'datetime.datetime'>
# Use the strftime on the datetime object directly
datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
# '2022-06-04 23:13:27'
type(datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S'))
# <class 'str'>

What datetime format string is 2017-01-05T14:23:33.986-0500 in Python

I have a string:
t = "2017-01-05T14:23:33.986-0500"
I need to convert it to a Python date.
I used:
t_obj = datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%f')
I think it is in YYYY-MM-DD with time as HH:MM:SS.sss , but am not able to figure out what -0500 could be...could it be subtracting -5 hrs for UTC?
Any help would be greatly appreciated
%z is what you need it's the timezone offset from UTC, see the docs
%z - UTC offset in the form +HHMM or -HHMM (empty string if the the object
is naive). (empty), +0000, -0400, +1030
In [89]:
t= "2017-01-05T14:23:33.986-0500"
dt.datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%f%z')
Out[89]:
datetime.datetime(2017, 1, 5, 14, 23, 33, 986000, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))
EdChum's answer is definitely correct. However, there is an easier way to go about parsing dates - python-dateutil:
>>> from dateutil.parser import parse
>>> parse("2017-01-05T14:23:33.986-0500")
datetime.datetime(2017, 1, 5, 14, 23, 33, 986000, tzinfo=tzoffset(None, -18000))
The parse() function is very robust and able to handle a wide variety of date formats:
>>> parse("Friday January 6, 2017 11:12 AM")
datetime.datetime(2017, 1, 6, 11, 12)
This is on 3.6.0 with dateutil 2.6.0.

How to convert the following string to python date?

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)

Categories

Resources