Talha Latif
Talha Latif

Reputation: 143

localize date time in python

Overview I receive the timestamp from server_x, my application is on server_y, both are in different regions, my application calls server_x api and receives json which has timestamp, now i need to perform some calculation on server_y, for that i need to make sure that the timestamp i receive from server_x could be used to covert the local datetime of server_y , so both are in sync

I want to convert datetime.now() to the timezone I receive from server for e.g., UTC-07:00

Current solution, I pass server_timestamp to the function and then I pass its zone info to the datetime.now

    Server_timestamp = "2020-04-04T10:24:49.000-0700"
    dt = datetime.strptime(Server_timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")
    convert_local = datetime.now(dt.tzinfo)

Problem: I need to save the timezone of the server in db and then use that instead of passing server_timestamp everytime, the tzinfo gives a type datetime.timezone = UTC-07:00, after storing this string how can I use it to change the localtime.

Upvotes: 1

Views: 4669

Answers (2)

Talha Latif
Talha Latif

Reputation: 143

I implemented a solution. I now save the last 5 char of the timestamp in the db "-0700".

time_zone = query_from_db
tz = datetime.strptime(time_zone, "%z")
datetime_now = datetime.now(tz.tzinfo)

Upvotes: 0

webb
webb

Reputation: 585

Here's a function that utilizes the datetime library to convert a datetime object from one timezone to another:

from datetime import datetime
import pytz

def convert_tz(dt, current_tz, out_tz):
    return dt.replace(tzinfo=current_tz).astimezone(tz=out_tz)

now = datetime.now(tz=pytz.timezone('US/Eastern'))
convert = datetime.now().astimezone().tzinfo

print(now)
print(utc_to_local(now, now.tzinfo, convert))

Output:

2020-05-10 17:02:44.245703-04:00
2020-05-10 16:02:44.245703-05:00

I used the pytz library for demonstration purposes. For you, to get the server's timezone, use the line datetime.now().astimezone().tzinfo.

Upvotes: 1

Related Questions