Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python set datetime to UTC timezone

I have an event I would like to trigger in Python, every weekend between Friday morning and Sunday morning.

I have wrote some code that works on my local environment but I'm afraid when deployed to production, the date time will be localised and the trigger will be incorrect. Ideally I would like everything to be synced to UTC, here's my attempt - I'd like to see if it's correct and if anyone has feedback on how to make it cleaner.

(The code works for me but I'm in the correct timezone anyway :) )

from datetime import datetime
def eventTrigger():
    if((datetime.weekday(datetime.today()) == 4) and (datetime.now().utcnow.hour) > 9):
        return True
    elif ((datetime.weekday(datetime.today()) == 6) and (datetime.now().utcnow.hour) < 10):
        return True
    elif (datetime.weekday(datetime.today()) == 5):
        return True
    else:
        return False

I tried reading the datetime documentation but it's pretty confusing.

like image 270
AllynH Avatar asked Dec 18 '22 07:12

AllynH


1 Answers

If you want to do this with the Python 3 standard library and without external dependency on pytz:

from datetime import datetime, timezone

now_utc = datetime.utcnow().replace(tzinfo=timezone.utc)
today_utc = now_utc.date()
like image 113
roskakori Avatar answered Dec 21 '22 11:12

roskakori