Timezone getting removed in python flask

Viewed 250

After a user logs in, I am setting a session variable to the time with utc.. but the timezone is getting stripped.

import datetime
from pytz import timezone
utc = timezone('utc')
session['login_time'] = datetime.datetime.now(utc)

When I print after the assignment the timezone is there 2021-06-11 23:56:00.161971+00:00. And a decorator function gets called. When I print session['login_time'] the timezone is removed. 2021-06-11 23:56:00

2 Answers

For me, I will use .strftime to help format the datetime and %Z is to show the timezone.

You can see the strftime document to help you format the time. I will use this code to replace your original one:

session['login_time'] = datetime.datetime.now(utc).strftime('"%Y-%m-%d %H:%M:%S%Z"')
login_time = datetime.datetime.strptime(session['login_time'],"%Y-%m-%d %H:%M:%S%Z" )
utct = utc.localize(login_time)
print(utct)
print(type(utct))

And here is the output:

2021-06-12 01:00:23+00:00
<class 'datetime.datetime'>

I had to re-add the timezone('utc') when i needed to use the time in another function.

def diff_min(t):
    utc = timezone('utc')
    t = utc.localize(t)
Related