0

I have a list of users:

tom, 0530, eastern
dick, 0745, pacific
harry, 0915, central
ect...

I need to send them an email at that specific time (or within 5 minutes) for their timezone. I've been working on a python script that I would run with cron every 5 minutes.

## pseudo code:
for user in users:
  if difference of usertime and utctime is <= 5 minutes:
    send email

I'm getting close, but doing the math with the converted timezones is where I'm stuck now.

code:

import datetime
import pytz
today = datetime.datetime.now().date()
user1 = pytz.timezone('US/Eastern').localize(datetime.datetime(today.year, today.month, today.day, 5, 30)) 
now_utc = datetime.datetime.now(pytz.timezone('UTC'))
user1_converted = user1.astimezone(pytz.timezone('UTC'))
now_utc - user1_converted
##maths
Kieran
  • 2,554
  • 3
  • 26
  • 38
Gaudard
  • 149
  • 1
  • 9

1 Answers1

1

We call this "making a mountain out of a mole hill" :)

It sounds like you have user preferences for the time they would like to be emailed, and the time zone they are part of.

E.g. tom = ('US/Eastern', "09:15")

When your script runs the first thing it must do is establish the current time in UTC.

from datetime import datetime
current_time = datetime.utcnow()

Then you need to convert the user's current time, and preference time, into UTC time. From this question.

tz = timezone('US/Pacific')
def toUTC(d):
    return tz.normalize(tz.localize(d)).astimezone(pytz.utc)

After you have done this you can subtract one from the other and compare to your set threshold (5 minutes) to see if it's the right time to send the email.

Community
  • 1
  • 1
Kieran
  • 2,554
  • 3
  • 26
  • 38