18

As the question says, I have a series of strings like '2020-01-06T00:00:00.000Z'. How can I convert this series to datetime using Python? I prefer the method on pandas. If not is there any method to solve this task? Thank all.

string '2020-01-06T00:00:00.000Z' 
convert to 2020-01-06 00:00:00 under datetime object
accdias
  • 5,160
  • 3
  • 19
  • 31
ShanN
  • 831
  • 1
  • 9
  • 20
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Dec 02 '21 at 12:41
  • 1
    a simple way how to handle the Z and parse to aware datetime / UTC: [replace with +00:00](https://stackoverflow.com/a/62769371/10197418). – FObersteiner Dec 02 '21 at 12:41

4 Answers4

19

With Python 3.7+, that can be achieved with datetime.fromisoformat() and some tweaking of the source string:

>>> from datetime import datetime
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1] + '+00:00')
datetime.datetime(2020, 1, 6, 0, 0, tzinfo=datetime.timezone.utc)
>>> 

And here is a more Pythonic way to achieve the same result:

>>> from datetime import datetime
>>> from datetime import timezone
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
datetime.datetime(2020, 1, 6, 3, 0, tzinfo=datetime.timezone.utc)
>>> 

Finally, to format it as %Y-%m-%d %H:%M:%S, you can do:

>>> d = datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2020-01-06 00:00:00'
>>>
accdias
  • 5,160
  • 3
  • 19
  • 31
6

Given raw_time is column contains the string time. You can do this

pd.to_datetime(df['raw_time'])
hunzter
  • 554
  • 4
  • 11
3

You can use python-dateutil

from dateutil import parser
parser.isoparse("2020-01-06T00:00:00.000Z")
Nwawel A Iroume
  • 1,249
  • 3
  • 21
  • 42
1

If you want pandas method try this:

sample series `s`

Out[1792]:
0    2020-01-06T00:00:00.000Z
1    2020-01-06T01:00:00.000Z
dtype: object

s_time = pd.to_datetime(s).dt.tz_localize(None)

Out[1796]:
0   2020-01-06 00:00:00
1   2020-01-06 01:00:00
dtype: datetime64[ns]
Andy L.
  • 24,909
  • 4
  • 17
  • 29