Forums

Timezone error with flask

I get user input datetime-local and save it to my database as UTC timezone, my code on localhost works perfectly fine, but on pythonanywhere it'll always save the time to db as user timezone not UTC, I found on StackOverflow I did as suggested but it didn't work (the question was about django) so any ideas how can I fix this error in flask ^^

Could you show us the relevant bits of your code?

This is how I get the utc time to compare with

   now = datetime.datetime.utcnow().replace(tzinfo=utc)
    time_string = now.strftime("%Y-%m-%d %H:%M:%S")
    time = datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')

And then here is my function to change user input into UTC time:

def convert_to_utc(user_datetime_local, user_timezone):

    timezone_name_dict = {
    '+00:00': 'UTC',
    '+01:00': 'Europe/London',
    '+02:00': 'Europe/Paris',
    # ... key value pairs for each time zone
}

    user_datetime_local_date = datetime.datetime.fromisoformat(user_datetime_local)
    user_datetime_local_format = user_datetime_local_date.strftime("%Y-%m-%d %H:%M:%S")
    user_datetime_local_obj = datetime.datetime.strptime(user_datetime_local_format, '%Y-%m-%d %H:%M:%S')
    user_timezone_obj = timezone(timezone_name_dict[user_timezone])


    utc_datetime = user_datetime_local_obj.astimezone(user_timezone_obj).astimezone(timezone('UTC'))

    return utc_datetime

and that's it for manipulating the time in my code.

A better designed code will save the day ^^

utc_datetime = user_datetime_local_date.astimezone(user_timezone_obj).astimezone(utc)
utc_datetime = user_timezone_obj.localize(user_datetime_local_date).astimezone(utc)

return timezone('UTC').normalize(utc_datetime)

Maybe add some logging to those functions so you could track the state of the code and see where it behaves differently than you'd expect.