Reputation: 57431
I'm looking to build a Python application which will receive timezone information from an Android phone, which I'd like to convert to a datetime tzinfo object (for example, as implemented by pytz).
This little Java program shows a 'sample' of the formats for TimeZone
available:
import java.util.TimeZone;
public class GetLocalTimeZone {
public static void main(String []args) {
TimeZone local_tz = TimeZone.getDefault();
System.out.println(local_tz.getDisplayName());
System.out.println(local_tz.getID());
System.out.println(local_tz.getRawOffset());
}
}
which prints
Central European Time
Europe/Amsterdam
3600000
In accordance with the TimeZone documentation, the getRawOffset()
function returns "the amount of time in milliseconds to add to UTC to get standard time in this time zone". This seems like a good starting point to instantiate a datetime.tzinfo
object.
The problem is that although I can instantiate one using the output of the getID()
method, e.g.
import pytz
amsterdam = pytz.timezone('Europe/Amsterdam')
I'm not sure how to instantiate a timezone
with the numerical offset, even if I convert it to hours. For example,
pytz.timezone('+01:00')
yields a UnknownTimeZoneError
. How would I go about creating a datetime.tzinfo
object from the offset from UTC (in milliseconds)? (I'm also open to other implementations such as Arrow and Pendulum).
Upvotes: 2
Views: 922
Reputation: 35613
Your problem is that a timezone includes both an offset, and daylight savings information.
There can be timezones with the same offset but which do daylight savings differently, so the offset alone is not sufficient to identify the timezone.
If possible, you should use the Display Name and/or ID.
If you can't do that, your best bet is to enumerate all timezones, and get a shortlist based on which ones have that offset for at least part of the year. Then you will have to pick one somehow.
Upvotes: 2