Date Time Formats in Python Date Time Formats in Python python python

Date Time Formats in Python


That extra .000 is micro seconds.

This will convert a date string of a format to datetime object.

import datetimed1 = datetime.datetime.strptime("2013-07-12T07:00:00Z","%Y-%m-%dT%H:%M:%SZ")d2 = datetime.datetime.strptime("2013-07-10T11:00:00.000Z","%Y-%m-%dT%H:%M:%S.%fZ")

Then convert them into any format depending on your requirement, by using:

new_format = "%Y-%m-%d"d1.strftime(new_format)


perhaps use .isoformat()

string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]

>>> import datetime>>> datetime.datetime.utcnow().isoformat() + "Z"'2013-07-11T22:26:51.564000Z'>>>

Z specifies "zulu" time or UTC.

You can also add the timezone component by making your datetime object timezone aware by applying the appropriate tzinfo object. With the tzinfo applied the .isoformat() method will include the appropriate utc offset in the output:

>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)>>> d.isoformat()'2019-11-11T00:52:43.349356+00:00'

You can remove the microseconds by change the microseconds value to 0:

>>> no_ms = d.replace(microsecond=0)>>> no_ms.isoformat()'2019-11-11T00:52:43+00:00'

Also, as of python 3.7 the .fromisoformat() method is available to load an iso formatted datetime string into a python datetime object:

>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)

http://www.ietf.org/rfc/rfc3339.txt


you can try to trim the string

data = "2019-10-22T00:00:00.000-05:00"result1 = datetime.datetime.strptime(data[0:19],"%Y-%m-%dT%H:%M:%S")result2 = datetime.datetime.strptime(data[0:23],"%Y-%m-%dT%H:%M:%S.%f")result3 = datetime.datetime.strptime(data[0:9], "%Y-%m-%d")