1

I am writing a python script that adds new events to user's calendars, assuming that the user's timezone is unknown. But since the StartDateTime and EndDateTime I set are always in UTC, and not the user's own timezone, they show up as different times on the user's calendar. For example, when I insert this:

{'Subject': 'Meeting', 'StartDateTime':'2017-07-01T14:15:00', 
'EndDateTime': '2017-07-01T16:15:00'}

The event shows up in the user's calendar as starting at 7:15AM and ending at 9:15AM (the user's timezone in this case is America/Los_Angeles).

I've read that Salesforce API uses UTC, so it doesn't appear like I can insert times in other timezones. To get around this, I've considered doing this:

  1. Get the user's timezone and offset
  2. Add the offset to the time I want to set to
  3. Add the event with the new time

However, I am currently stuck on step 1. I was able to get the user's timezone by querying for the TimeZoneSidKey, but that doesn't show the offset. I've searched around and seen people make a list of all TimeZoneSidKey and their offsets in a CSV file and get the offsets by searching through that file. But that requires a lot of overhead and I was wondering if there are faster ways to achieve this?

I'd appreciate any ideas on either how to get the offset quickly, or if possible, a straight-forward way to insert an event that'll show up as the intended time in the user's calendar, regardless of the timezone that user is at.

  • You'll probably want to take a peek at pytz which provides timezone to tzinfo-style conversions. So, your basic process will indeed be (a) get user's TimezoneSidKey, (b) convert events to UTC, and (c) insert/update records, just as you'd already guessed. – sfdcfox Jul 1 '17 at 0:36
  • Thanks a lot! The pytz library was just what I needed. I ended up using timezone(TimezoneSidKey).utcoffset(mytime) to get the offset and convert my time to UTC before inserting it. – jasep Jul 3 '17 at 22:41
0

As sfdcfox said, having Python do the conversion is definitely a viable way of handling it.

Another option is... you could create a hidden checkbox on Event, let's call it Adjust__c. This box never gets ticked except when adding the Event by the API. So when you're submitting an event from Python, tick that box to tell Salesforce the event needs to be shifted to the user's time zone rather than GMT.

Then you'd set up a before insert Apex trigger which kicks in if Adjust__c is ticked. (Bulkify this as needed of course.) It queries the event's user's time zone, and uses the Apex TimeZone class to obtain the correct offset from that zone. Then it sets the adjusted times and Adjust__c = false in Trigger.New.

You'll of course also have to ensure there are no before insert triggers that run prior to this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.