简体   繁体   中英

How to calculate utc in local time on ubuntu with python 3.8

I have a web application writen in python 3.8 running on an ubuntu server (18.04). Requests to the server are processed by a nginx server.

It is possible to upload pdf and excel files and the website should show the date and time the files were uploaded. This is working but the utc time is shown and I want the website to show the actual local time (Europe/Berlin UTC +1/+2). So I just tried to convert the time within the python code:

utc_diff = 1
cur_time = time.time()

if time.localtime(cur_time).tm_isdst: # check summer / winter time
>> utc_diff = 2

... (datetime.fromtimestamp(round(timestamp)) + timedelta(hours=utc_diff))

or

utc = datetime.utcnow()
ltz = datetime.astimezone(utc)
diff = str(ltz).split("+")
diff = diff[1].split(":")

... datetime.fromtimestamp(round(timestamp)) + timedelta(hours=int(diff))

The problem is that I just can calcualte for example +2 hours but if I want to use any fucntions of the time or datetime module it just works on my local windows pc but not on the server.

The line datetime.fromtimestamp(round(timestamp)) + timedelta(hours=int(diff)) is working locally and on the server.

How I have to code this to make it work on the server?

I don't think you want to do the time offset by hand. I think you want soemthing more like:

import time

now = time.time()
print(time.strftime("%H:%M:%S", time.gmtime(now)))
print(time.strftime("%H:%M:%S", time.localtime(now)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM