0

How can I change this naive time to UTC time in python

The time is 2021-08-05T08:32:47.362000Z

st= "2021-08-05T08:32:47.362000Z"

dt = datetime.strptime(st,"%Y-%m-%d %H:%M:%S.%fZ")

I don't know how to parse this time in python. The above given code is what I know I don't know to parse this time.

So this time has been fetched from Django database and what I inserted is a UTC time and I got the above time as a result.

The thing is I need to get utc time.

hamere
  • 65
  • 1
  • 7
  • This has already been answered in: https://stackoverflow.com/questions/1595047/convert-to-utc-timestamp – Sefan Aug 05 '21 at 11:48
  • 1
    It also has been answered for [your other question](https://stackoverflow.com/q/68664644/10197418) (except for the 'T' in the date/time string). – FObersteiner Aug 05 '21 at 11:52
  • basically a duplicate of [how-do-i-parse-an-iso-8601-formatted-date](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Aug 05 '21 at 11:54
  • 1
    Please clarify in how [your earlier question](https://stackoverflow.com/questions/68664644/how-can-i-convert-from-utc-time-to-local-time-in-python) does not cover this one as well. From the looks of it, the only "issue" is replacing a space with a T in the expected format. – MisterMiyagi Aug 05 '21 at 12:02

1 Answers1

-2

You are missing 'T':

dt = datetime.strptime(st,"%Y-%m-%dT%H:%M:%S.%fZ")

You could use pytz to modify timezone as you wish. here

Panda
  • 87
  • 11
  • that does not return aware datetime – FObersteiner Aug 05 '21 at 11:53
  • the OP wants "UTC time", i.e. the 'Z' (zulu time) should be parsed to UTC (datetime object with tzinfo=timezone.utc). your parsing directive just ignores that by using a literal Z. – FObersteiner Aug 05 '21 at 12:16
  • ...and with uncertainty in the way OP posed the question about the current timezone (which he added later), I provided OP a method in which OP can achieve this and more, well explained in the post linked. A different method to yours, but not wrong? So why downvote? – Panda Aug 05 '21 at 12:19
  • because I think it is bad practice to use naive datetime here as it is taken for *local time* in Python, not UTC (as in many other languages). That's a pitfall when working with datetime in Python and should therefore not be suggested especially to people new to the language. – FObersteiner Aug 05 '21 at 12:23
  • Q: How to convert a **naive time** to UTC time in python? Problem you have appears to be with the way the question has been asked, not my answer – Panda Aug 05 '21 at 12:24
  • that's a different story (yes, "2021-08-05T08:32:47.362000Z" is not *naive* in that sense), but I still think your answer is misleading. – FObersteiner Aug 05 '21 at 12:30