There have been so many times when I wanted to have a datetime show in UTC. I am not talking about simply looking at the time and acting as if it is in UTC. For example let’s say that I want to express the current time in UTC. This is how you do it:

from datetime import datetime, timezone
dt_now = datetime(2021, 1, 1, 12, 34, 56).astimezone(timezone.utc)
print(repr(dt_now))

If I run the above code in Python 3.6 or above in New York (UTC-0500) the following will be the result:

datetime.datetime(2021, 1, 1, 17, 34, 56, tzinfo=datetime.timezone.utc)

Let’s say that now you want to display this date the same way that JavaScript would display when using JS code like the following:

let dt = new Date(2021, 0, 1, 21, 34, 56);
let strDT = JSON.stringify(dt);
console.log(strDT); // "2021-01-02T02:34:56.000Z"

In order to do the same in Python 3.6 I can use something like the following:

import json
from datetime import datetime, timezone
dt = datetime(2021, 1, 1, 21, 34, 56).astimezone(timezone.utc)
str_dt = dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
print(json.dumps(str_dt)) # "2021-01-02T02:34:56.000Z"

Happy coding! šŸ˜Ž

Categories: BlogJavaScriptPython

Leave a Reply

Your email address will not be published. Required fields are marked *