AllynH
AllynH

Reputation: 166

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.

Upvotes: 5

Views: 15891

Answers (2)

roskakori
roskakori

Reputation: 3336

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()

Upvotes: 10

Max Power
Max Power

Reputation: 8954

Datetimes and timezones are confusing, it's good you're making sure to be deliberate here.

First, library pytz can help

from datetime import datetime
import pytz

Then, you can define today and now variables, to be reliably UTC, at the top of your eventTrigger() with:

now_utc   = datetime.now(pytz.utc) 
today_utc = now_utc.date()

Upvotes: 8

Related Questions