Scheduled messages are sent at difference of 5 hours 30 minutes in Twilio and Sendgrid api

I am working on a Django application where I have used twilio to send sms and whatsapp messages and the sendgrid api for sending the emails. The problem occurs in scheduled messages in all three. For example, if I have schedule an email to be sent at 06:24 PM(scheduled time is 06:24 PM), then I am receiving the email at 11:54 PM, hence the difference is of 5 hours and 30 minutes. The same problem also arises in sms and whatsapp.

I think the problem might be due to the timezone. I am scheduling the messages from India and twilio account is in USA. And, the time difference of 5 hours 30 mins is due to the UTC format as India is 5 hours 30 mins ahead of UTC. But I am not getting any solution for this.

So, is there any specific way to solve this problem ?

The issue is that Twilio and SendGrid are scheduling the messages in UTC and you are creating your time in IST without a time zone attached, so the time is being interpreted as UTC and thus sent 5 hours 30 minutes out.

I'm not a python expert, so I may be wrong here. But, I think using mktime is incorrect here and you should be using gmtime.

message = MAIL(...)
finalScheduleTime = int(time.gmtime(scheduleTime.timetuple()))
message.send_at = finalScheduleTime

Alternatively, you don't have to convert the datetime to a time first. You can change the datetime's timezone from your local one to UTC:

import pytz

utcdatetime = scheduleTime.astimezone(pytz.UTC)

Then turn that into a timestamp:

message.send_at = int(utcdatetime.timestamp())

As per the answer of philnash, the sendgrid api and twilio is scheduling the messages in UTC and we are generating it in IST without timezone attached. Hence first of all we need to attach the timezone and then convert it in the UNIX Timestamp. Refer to the following code:

scheduleTime = scheduleTime.astimezone()
finalScheduleTime = int(time.mktime(scheduleTime.timetupple()))
message.send_at = finalScheduleTime 

Hence, this will solve the problem.

Back to Top