Get all available timezones - python

I'm currently working on an application that is required to support multiple timezones.
For that, I'm using the dateutil library. Now, I need a way to present the user a list of all available timezones the dateutil library supports.
Also, is it advisable to store the tz as strings in the database like "Europe/Berlin"?

dateutil will use the OS timezone info, but does carry it's own compressed timezone info file too.
You could list the available names from the utility code that loads this data:
from dateutil.zoneinfo import get_zonefile_instance
zonenames = list(get_zonefile_instance().zones)
You'd need to sort and filter that list a little; there are both abbreviated (3 letter) timezone codes as well as "region/city" entries in this list.
Storing those names in a database is just fine.
Note that this loads all data into memory; if that's not desirable you'd need to load the tar file yourself:
import os
import tarfile
import dateutil.zoneinfo
zi_path = os.path.abspath(os.path.dirname(dateutil.zoneinfo.__file__))
zonesfile = tarfile.TarFile.open(
os.path.join(zi_path, dateutil.zoneinfo.ZONEFILENAME))
zonenames = [zn.name for zn in zonesfile.getmembers()
if not zn.isdir() and zn.name != dateutil.zoneinfo.METADATA_FN]

For dateutil:
from dateutil.zoneinfo import getzoneinfofile_stream, ZoneInfoFile
ZoneInfoFile(getzoneinfofile_stream()).zones.keys()
>>> ['Asia/Ujung_Pandang',
'America/Porto_Velho',
'America/La_Paz',
'America/Caracas',
'Europe/Malta',
'Etc/GMT-13',
'Atlantic/Bermuda',
...]
pytz is a little easier
import pytz
pytz.all_timezones
>>> ['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
'Africa/Algiers',
'Africa/Asmara',
'Africa/Asmera',
'Africa/Bamako',
'Africa/Bangui',
'Africa/Banjul',
'Africa/Bissau',
'Africa/Blantyre',
'Africa/Brazzaville',
...]
Note that dateutil prefers to use the operating system to determine timezone info. pytz uses its own zone files. While there are probably advantages to each, pytz provides more consistency if you don't want to manage time zones at the system level.

Related

datetime.now() gets different time than the one my pc has configured

I've been looking through this sites posts on this issue i have, and none of them solve my problem so far. What happens is that my datetime.now() method from datetime module doesnt show time as configured in my pc, so here i did some tests in order to figure out what's happening. a few minutes ago I solved it by specifying the timezone through dateutil module, but it shouldn't be done in that way.
Note: I'm currently using Ubuntu/Linux OS, and use a virtual environment for my project.
CODE:
from dateutil import tz
from datetime import date, datetime, time
date1 = datetime.now(tz.tzlocal()) # it works not at all
date1_ = datetime.now() # Same thing
date2 = datetime.now(tz.gettz('Cuba')) # it does now
date1_tz_info = date1.timetz()
print(date1, date1_, date2, sep='\n')
print(date1_tz_info)
OUTPUT:
2021-01-19 22:39:13.960834+00:00
2021-01-19 22:39:13.960874
2021-01-19 17:39:13.961087-05:00 #The Right Output
22:39:13.960834+00:00
Picture from pc
So as far as seen now datetime.now() returns value as if it was utc +00:00.
In Python 3.x, local timezone can be figured out like this:
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
if the python version is before 3.6 you can use
import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo
From that we can see which timezone python thinks is local. How to change the time zones for windows 10 is below
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
After over 2 hours of research i came across an answer.
A few points to be told before getting to it:
it turns out that the problem had to do with the virtual environment that i have set, (it wasn't able to use variables exported from .bashrc file (for some reason the TZ var i exported from .bashrc doesnt exist in my virtualenv), so this approach from start in the end didnt work).
So... i thought on exporting them via a file on /etc/profile.d/ path, so it could be seen across all shells for all users.
Then... after losing some of my hair trying to figure out what on earth was happening, it resulted that virtualenv direnv was creating/deleting/modifying variables according to the path i was at.
Finally, what i did is to add export TZ='America/Havana' in .envrc file which is located at one's project root folder, allowed it from direnv program then reloaded, afterwards i typed the following to check my solution.
>>> import os
>>> os.environ['TZ']
'America/Havana'
>>> import datetime
>>> print(datetime.datetime.now())
2021-01-20 00:21:00.189968
>>> print(datetime.datetime.now().astimezone())
2021-01-20 00:21:16.195877-05:00
>>>
As you can appreciate, finally... at last.. the time zone difference between UTC (00:00) and mine is taken into account for unaware datetime objects.
Note: I am a rookie regarding to Python and Linux operating systems, so if some of my words lack of fundament, please don't mind it.

Is there a way to get the current time zone in the format the Google Calendar API wants in Python?

I'm trying to make a python app to interact with Google Calendar and I need help getting the time zone in the format it wants. I tried datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo,
but that just returned PST and I need it to be America/Los_Angeles.
Any suggestions?
You can use pytz to localize datetime objects in python.
import datetime
import pytz
today = datetime.datetime.now()
localized = pytz.timezone('America/Los_Angeles').localize(today)
You can change the timezone by changing the value of os.environ["TZ"]:
Sample Code:
import os
import time
os.environ["TZ"] = "America/New_York"
time.tzset()
From there, you can change the format of date by using time.strftime(format)
References:
https://docs.python.org/3/library/datetime.html
https://help.pythonanywhere.com/pages/SettingTheTimezone/

using pytz to get local timezone name [duplicate]

How do I get the Olson timezone name (such as Australia/Sydney) corresponding to the value given by C's localtime call?
This is the value overridden via TZ, by symlinking /etc/localtime, or setting a TIMEZONE variable in time-related system configuration files.
I think best bet is to go thru all pytz timezones and check which one matches local timezone, each pytz timezone object contains info about utcoffset and tzname like CDT, EST, same info about local time can be obtained from time.timezone/altzone and time.tzname, and I think that is enough to correctly match local timezone in pytz database e.g.
import time
import pytz
import datetime
local_names = []
if time.daylight:
local_offset = time.altzone
localtz = time.tzname[1]
else:
local_offset = time.timezone
localtz = time.tzname[0]
local_offset = datetime.timedelta(seconds=-local_offset)
for name in pytz.all_timezones:
timezone = pytz.timezone(name)
if not hasattr(timezone, '_tzinfos'):
continue#skip, if some timezone doesn't have info
# go thru tzinfo and see if short name like EDT and offset matches
for (utcoffset, daylight, tzname), _ in timezone._tzinfos.iteritems():
if utcoffset == local_offset and tzname == localtz:
local_names.append(name)
print local_names
output:
['America/Atikokan', 'America/Bahia_Banderas',
'America/Bahia_Banderas', 'America/Belize', 'America/Cambridge_Bay',
'America/Cancun', 'America/Chicago', 'America/Chihuahua',
'America/Coral_Harbour', 'America/Costa_Rica', 'America/El_Salvador',
'America/Fort_Wayne', 'America/Guatemala',
'America/Indiana/Indianapolis', 'America/Indiana/Knox',
'America/Indiana/Marengo', 'America/Indiana/Marengo',
'America/Indiana/Petersburg', 'America/Indiana/Tell_City',
'America/Indiana/Vevay', 'America/Indiana/Vincennes',
'America/Indiana/Winamac', 'America/Indianapolis', 'America/Iqaluit',
'America/Kentucky/Louisville', 'America/Kentucky/Louisville',
'America/Kentucky/Monticello', 'America/Knox_IN',
'America/Louisville', 'America/Louisville', 'America/Managua',
'America/Matamoros', 'America/Menominee', 'America/Merida',
'America/Mexico_City', 'America/Monterrey',
'America/North_Dakota/Beulah', 'America/North_Dakota/Center',
'America/North_Dakota/New_Salem', 'America/Ojinaga',
'America/Pangnirtung', 'America/Rainy_River', 'America/Rankin_Inlet',
'America/Resolute', 'America/Resolute', 'America/Tegucigalpa',
'America/Winnipeg', 'CST6CDT', 'Canada/Central', 'Mexico/General',
'US/Central', 'US/East-Indiana', 'US/Indiana-Starke']
In production you can create such a mapping beforehand and save it instead of iterating always.
Testing script after changing timezone:
$ export TZ='Australia/Sydney'
$ python get_tz_names.py
['Antarctica/Macquarie', 'Australia/ACT', 'Australia/Brisbane',
'Australia/Canberra', 'Australia/Currie', 'Australia/Hobart',
'Australia/Lindeman', 'Australia/Melbourne', 'Australia/NSW',
'Australia/Queensland', 'Australia/Sydney', 'Australia/Tasmania',
'Australia/Victoria']
This is kind of cheating, I know, but getting from '/etc/localtime' doesn't work for you?
Like following:
>>> import os
>>> '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
'Australia/Sydney'
Hope it helps.
Edit: I liked #A.H.'s idea, in case '/etc/localtime' isn't a symlink. Translating that into Python:
#!/usr/bin/env python
from hashlib import sha224
import os
def get_current_olsonname():
tzfile = open('/etc/localtime')
tzfile_digest = sha224(tzfile.read()).hexdigest()
tzfile.close()
for root, dirs, filenames in os.walk("/usr/share/zoneinfo/"):
for filename in filenames:
fullname = os.path.join(root, filename)
f = open(fullname)
digest = sha224(f.read()).hexdigest()
if digest == tzfile_digest:
return '/'.join((fullname.split('/'))[-2:])
f.close()
return None
if __name__ == '__main__':
print get_current_olsonname()
One problem is that there are multiple "pretty names" , like "Australia/Sydney" , which point to the same time zone (e.g. CST).
So you will need to get all the possible names for the local time zone, and then select the name you like.
e.g.: for Australia, there are 5 time zones, but way more time zone identifiers:
"Australia/Lord_Howe", "Australia/Hobart", "Australia/Currie",
"Australia/Melbourne", "Australia/Sydney", "Australia/Broken_Hill",
"Australia/Brisbane", "Australia/Lindeman", "Australia/Adelaide",
"Australia/Darwin", "Australia/Perth", "Australia/Eucla"
you should check if there is a library which wraps TZinfo , to handle the time zone API.
e.g.: for Python, check the pytz library:
http://pytz.sourceforge.net/
and
http://pypi.python.org/pypi/pytz/
in Python you can do:
from pytz import timezone
import pytz
In [56]: pytz.country_timezones('AU')
Out[56]:
[u'Australia/Lord_Howe',
u'Australia/Hobart',
u'Australia/Currie',
u'Australia/Melbourne',
u'Australia/Sydney',
u'Australia/Broken_Hill',
u'Australia/Brisbane',
u'Australia/Lindeman',
u'Australia/Adelaide',
u'Australia/Darwin',
u'Australia/Perth',
u'Australia/Eucla']
but the API for Python seems to be pretty limited, e.g. it doesn't seem to have a call like Ruby's all_linked_zone_names -- which can find all the synonym names for a given time zone.
If evaluating /etc/localtime is OK for you, the following trick might work - after translating it to python:
> md5sum /etc/localtime
abcdefabcdefabcdefabcdefabcdefab /etc/localtime
> find /usr/share/zoneinfo -type f |xargs md5sum | grep abcdefabcdefabcdefabcdefabcdefab
abcdefabcdefabcdefabcdefabcdefab /usr/share/zoneinfo/Europe/London
abcdefabcdefabcdefabcdefabcdefab /usr/share/zoneinfo/posix/Europe/London
...
The duplicates could be filtered using only the official region names "Europe", "America" ... If there are still duplicates, you could take the shortest name :-)
Install pytz
import pytz
import time
#import locale
import urllib2
yourOlsonTZ = None
#yourCountryCode = locale.getdefaultlocale()[0].split('_')[1]
yourCountryCode = urllib2.urlopen('http://api.hostip.info/country.php').read()
for olsonTZ in [pytz.timezone(olsonTZ) for olsonTZ in pytz.all_timezones]:
if (olsonTZ._tzname in time.tzname) and (str(olsonTZ) in pytz.country_timezones[yourCountryCode]):
yourOlsonTZ = olsonTZ
break
print yourOlsonTZ
This code will take a best-guess crack at your Olson Timezone based both on your Timezone Name (as according to Python's time module), and your Country Code (as according to Python's locale module the hostip.info project, which references your IP address and geolocates you accordingly).
For example, simply matching the Timzone Names could result in America/Moncton, America/Montreal, or America/New_York for EST (GMT-5). If your country is the US, however, it will limit the answer to America/New_York.
However, if your country is Canada, the script will simply default to the topmost Canadian result (America/Moncton). If there is a way to further refine this, please feel free to leave suggestions in comments.
The tzlocal module for Python is aimed at exactly this problem. It produces consistent results under both Linux and Windows, properly converting from Windows time zone ids to Olson using the CLDR mappings.
This will get you the time zone name, according to what's in the TZ variable, or localtime file if unset:
#! /usr/bin/env python
import time
time.tzset
print time.tzname
Here's another posibility, using PyICU instead; which is working for my purposes:
>>> from PyICU import ICUtzinfo
>>> from datetime import datetime
>>> datetime(2012, 1, 1, 12, 30, 18).replace(tzinfo=ICUtzinfo.getDefault()).isoformat()
'2012-01-01T12:30:18-05:00'
>>> datetime(2012, 6, 1, 12, 30, 18).replace(tzinfo=ICUtzinfo.getDefault()).isoformat()
'2012-06-01T12:30:18-04:00'
Here it is interpreting niave datetimes (as would be returned by a database query) in the local timezone.
I prefer following a slightly better than poking around _xxx values
import time, pytz, os
cur_name=time.tzname
cur_TZ=os.environ.get("TZ")
def is_current(name):
os.environ["TZ"]=name
time.tzset()
return time.tzname==cur_name
print "Possible choices:", filter(is_current, pytz.all_timezones)
# optional tz restore
if cur_TZ is None: del os.environ["TZ"]
else: os.environ["TZ"]=cur_TZ
time.tzset()
I changed tcurvelo's script to find the right form of time zone (Continent/..../City), in most of cases, but return all of them if fails
#!/usr/bin/env python
from hashlib import sha224
import os
from os import listdir
from os.path import join, isfile, isdir
infoDir = '/usr/share/zoneinfo/'
def get_current_olsonname():
result = []
tzfile_digest = sha224(open('/etc/localtime').read()).hexdigest()
test_match = lambda filepath: sha224(open(filepath).read()).hexdigest() == tzfile_digest
def walk_over(dirpath):
for root, dirs, filenames in os.walk(dirpath):
for fname in filenames:
fpath = join(root, fname)
if test_match(fpath):
result.append(tuple(root.split('/')[4:]+[fname]))
for dname in listdir(infoDir):
if dname in ('posix', 'right', 'SystemV', 'Etc'):
continue
dpath = join(infoDir, dname)
if not isdir(dpath):
continue
walk_over(dpath)
if not result:
walk_over(join(infoDir))
return result
if __name__ == '__main__':
print get_current_olsonname()
This JavaScript project attempts to solve the same issue in the browser client-side. It works by playing "twenty questions" with the locale, asking for the UTC offset of certain past times (to test for summer time boundaries, etc.) and using those results to deduce what the local time zone must be. I am not aware of any equivalent Python package unfortunately, so if someone wanted to use this solution it would have to be ported to Python.
While this formula will require updating every time (at worst) the TZ database is updated, a combination of this algorithm and the solution proposed by Anurag Uniyal (keeping only possibilities returned by both methods) sounds to me like the surest way to compute the effective local timezone. As long as there is some difference between the UTC offset of at least one local time in any two time zones, such a system can correctly choose between them.

Python specify file creation time by milliseconds

After some research I couldn't find any solution to this so here it goes:
Python's command:
time.ctime(os.path.getctime('/path'))
displays output as (e.g):
Fri Dec 2 16:06:05 2016.
How can I make it display not only hours/minutes/seconds but also milliseconds?
Use os.stat("/").st_ctime_ns gain nanoseconds level
import os
import datetime
datetime.datetime.fromtimestamp(os.stat("/").st_ctime_ns)
You can use stat:
import datetime
import os
datetime.datetime.fromtimestamp(os.stat('/').st_ctime)
Note that if you modified the metadata of the file, you will get this as the "ctime", getting the creation date after modification of metadata is not possible on UNIX platforms.

Python - how to read Windows "Media Created" date (not file creation date)

I have several old video files that I'm converting to save space. Since these files are personal videos, I want the new files to have the old files' creation time.
Windows has an attribute called "Media created" which has the actual time recorded by the camera. The files' modification times are often incorrect so there are hundreds of files where this won't work.
How can I access this "Media created" date in Python? I've been googling like crazy and can't find it. Here's a sample of the code that works if the creation date and modify date match:
files = []
for file in glob.glob("*.AVI"):
files.append(file)
for orig in files:
origmtime = os.path.getmtime(orig)
origatime = os.path.getatime(orig)
mark = (origatime, origmtime)
for target in glob.glob("*.mp4"):
firstroot = target.split(".mp4")[0]
if firstroot in orig:
os.utime(target, mark)
As Borealid noted, the "Media created" value is not filesystem metadata. The Windows shell gets this value as metadata from within the file itself. It's accessible in the API as a Windows Property. You can easily access Windows shell properties if you're using Windows Vista or later and have the Python extensions for Windows installed. Just call SHGetPropertyStoreFromParsingName, which you'll find in the propsys module. It returns a PyIPropertyStore instance. The property that's labelled "Media created" is System.Media.DateEncoded. You can access this property using the property key PKEY_Media_DateEncoded, which you'll find in propsys.pscon. In Python 3 the returned value is a datetime.datetime subclass, with the time in UTC. In Python 2 the value is a custom time type that has a Format method that provides strftime style formatting. If you need to convert the value to local time, the pytz module has the IANA database of time zones.
For example:
import pytz
import datetime
from win32com.propsys import propsys, pscon
properties = propsys.SHGetPropertyStoreFromParsingName(filepath)
dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
if not isinstance(dt, datetime.datetime):
# In Python 2, PyWin32 returns a custom time type instead of
# using a datetime subclass. It has a Format method for strftime
# style formatting, but let's just convert it to datetime:
dt = datetime.datetime.fromtimestamp(int(dt))
dt = dt.replace(tzinfo=pytz.timezone('UTC'))
dt_tokyo = dt.astimezone(pytz.timezone('Asia/Tokyo'))
If the attribute you're talking about came from the camera, it's not a filesystem permission: it's metadata inside the videos themselves which Windows is reading out and presenting to you.
An example of this type of metadata would be a JPEG image's EXIF data: what type of camera took the photo, what settings were used, and so forth.
You would need to open up the .mp4 files and parse the metadata, preferably using some existing library for doing that. You wouldn't be able to get the information from the filesystem because it's not there.
Now if, on the other hand, all you want is the file creation date (which didn't actually come from the camera, but was set when the file was first put onto the current computer, and might have been initialized to some value that was previously on the camera)... That can be gotten with os.path.getctime(orig).

Categories