7

Python Snippet – Datetimes In UTC

 3 years ago
source link: https://cwestblog.com/2021/04/10/python-snippet-datetimes-in-utc/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Python Snippet – Datetimes In UTC – Chris West's Blog

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! 😎


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK