How to enumerate all vaild timezone for Linux? - python

I'm working on a pre-configuration cloud-init script for Linux OS and need to list all vaild timezone for user to choose
Currently my approach is
cd /usr/share/zoneinfo/
find
However, this is giving some duplicated names in posix and right. And I'm not sure if all the correct names are included.
Is there anyway (python module or program) to enumerate all vaild linux timezone names?
Thanks

You can use the pytz library.
>>> import pytz
>>> for time_zone in pytz.all_timezones:
>>> print( time_zone )
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
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
Africa/El_Aaiun
Africa/Freetown
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Juba
Africa/Kampala
Africa/Khartoum
Africa/Kigali
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Timbuktu
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/ComodRivadavia
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Atka
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Buenos_Aires
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Catamarca
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Coral_Harbour
America/Cordoba
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Ensenada
America/Fort_Wayne
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Indianapolis
America/Inuvik
America/Iqaluit
America/Jamaica
America/Jujuy
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Knox_IN
America/Kralendijk
America/La_Paz
America/Lima
America/Los_Angeles
America/Louisville
America/Lower_Princes
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Matamoros
America/Mazatlan
America/Mendoza
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montreal
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Acre
America/Porto_Velho
America/Puerto_Rico
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Rosario
America/Santa_Isabel
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Shiprock
America/Sitka
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Virgin
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/South_Pole
Antarctica/Syowa
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Ashkhabad
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Calcutta
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Gaza
Asia/Harbin
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Istanbul
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Kathmandu
Asia/Katmandu
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Saigon
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Tel_Aviv
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faeroe
Atlantic/Faroe
Atlantic/Jan_Mayen
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/ACT
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Canberra
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/LHI
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/NSW
Australia/North
Australia/Perth
Australia/Queensland
Australia/South
Australia/Sydney
Australia/Tasmania
Australia/Victoria
Australia/West
Australia/Yancowinna
Brazil/Acre
Brazil/DeNoronha
Brazil/East
Brazil/West
CET
CST6CDT
Canada/Atlantic
Canada/Central
Canada/East-Saskatchewan
Canada/Eastern
Canada/Mountain
Canada/Newfoundland
Canada/Pacific
Canada/Saskatchewan
Canada/Yukon
Chile/Continental
Chile/EasterIsland
Cuba
EET
EST
EST5EDT
Egypt
Eire
Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/GMT0
Etc/Greenwich
Etc/UCT
Etc/UTC
Etc/Universal
Etc/Zulu
Europe/Amsterdam
Europe/Andorra
Europe/Athens
Europe/Belfast
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Nicosia
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
GB
GB-Eire
GMT
GMT+0
GMT-0
GMT0
Greenwich
HST
Hongkong
Iceland
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Iran
Israel
Jamaica
Japan
Kwajalein
Libya
MET
MST
MST7MDT
Mexico/BajaNorte
Mexico/BajaSur
Mexico/General
NZ
NZ-CHAT
Navajo
PRC
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Ponape
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Samoa
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Truk
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
ROC
ROK
Singapore
Turkey
UCT
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Pacific-New
US/Samoa
UTC
Universal
W-SU
WET
Zulu

Related

Time conversion from UTC to Europe/Warsaw

I'm trying to convert UTC time to Europe/Warsaw time. Warsaw time is now UTC + 2 hours. I don't know why I get result with time 30 minutes eariler. I'm parsing date from string similar to: 7:27:02 AM or 2:16:28 PM.
print(time_str) #6:47:46 PM
format = '%I:%M:%S %p'
time_obj = datetime.strptime(time_str, format)
utc_time = time_obj.replace(tzinfo=ZoneInfo('Etc/UTC'))
converted_time = utc_time.astimezone(tz=ZoneInfo('Europe/Warsaw')).time()
print(utc_time.time(), converted_time)
Output is
6:47:46 PM
18:47:46
20:11:46
While I expect:
6:47:46 PM
18:47:46
20:47:46
EDIT - this line fixed it:
time_obj = datetime.strptime(time_str, format).replace(year=2021, month=7, day=14)

I am always receiving an AttributeError

Here is my code:
import time
import datetime
import pytz
print('--'*62)
cont = 0
print('MENU'.center(115))
print('--'*62)
my_timezones = {}
l = list() # MAIN LIST
l.append('0')
my_timezones['United Arab Emirates'] = pytz.country_timezones['AE']
my_timezones['Canada'] = pytz.country_timezones['CA'][20]
my_timezones['South Korea'] = pytz.country_timezones['KR']
my_timezones['United States'] = pytz.country_timezones['US'][17]
my_timezones['New Zeland'] = pytz.country_timezones['NZ'][0]
my_timezones['Norway'] = pytz.country_timezones['NO']
my_timezones['Ireland'] = pytz.country_timezones['IE']
my_timezones['Netherlands'] = pytz.country_timezones['NL']
my_timezones['Switzerland'] = pytz.country_timezones['CH']
l.append(my_timezones['United Arab Emirates'])
l.append(my_timezones['Canada'])
l.append(my_timezones['South Korea'])
l.append(my_timezones['United States'])
l.append(my_timezones['New Zeland'])
l.append(my_timezones['Norway'])
l.append(my_timezones['Ireland'])
l.append(my_timezones['Netherlands'])
l.append(my_timezones['Switzerland'])
print(l)
print('Cod Country Timezone')
for c in my_timezones.keys():
cont+=1
print(f'{cont}', end=' ')
print(f'{c}', end='')
print(f'{my_timezones[c]}'.center(45))
print('--'*62)
while True:
which = int(input('Which one? '))
if which == 0:
break
else:
print(f'Local Time: {datetime.datetime.now()}')
print(f'UTC time: {datetime.datetime.utcnow()}')
try:
baby = l[which]
timezone = pytz.timezone(baby) # THE LINE WHERE IS NOT WORKING
time = datetime.datetime.now(tz=timezone)
print(f'{l[which]} time: {time}')
except IndexError:
print('SORRY! WE DIDN´T FIND IT!')
for c in l:
print(c)`` ``
Then I receive this error:
AttributeError: 'list' object has no attribute 'upper'
I really don´t know how to fix it, because I don´t know even what is the source of the problem, so please I need your help!
Hope this works for you.
code
import time
import datetime
import pytz
print('--'*62)
cont = 0
print('MENU'.center(115))
print('--'*62)
my_timezones = {}
l = list() # MAIN LIST
l.append('0')
my_timezones['United Arab Emirates'] = pytz.country_timezones['AE'][0]
my_timezones['Canada'] = pytz.country_timezones['CA'][20]
my_timezones['South Korea'] = pytz.country_timezones['KR'][0]
my_timezones['United States'] = pytz.country_timezones['US'][17]
my_timezones['New Zeland'] = pytz.country_timezones['NZ'][0]
my_timezones['Norway'] = pytz.country_timezones['NO'][0]
my_timezones['Ireland'] = pytz.country_timezones['IE'][0]
my_timezones['Netherlands'] = pytz.country_timezones['NL'][0]
my_timezones['Switzerland'] = pytz.country_timezones['CH'][0]
l.append(my_timezones['United Arab Emirates'])
l.append(my_timezones['Canada'])
l.append(my_timezones['South Korea'])
l.append(my_timezones['United States'])
l.append(my_timezones['New Zeland'])
l.append(my_timezones['Norway'])
l.append(my_timezones['Ireland'])
l.append(my_timezones['Netherlands'])
l.append(my_timezones['Switzerland'])
print(l)
print('Cod Country Timezone')
for c in my_timezones.keys():
cont+=1
print(f'{cont}', end=' ')
print(f'{c}', end='')
print(f'{my_timezones[c]}'.center(45))
print('--'*62)
while True:
wich = int(input('Wich one? '))
if wich == 0:
break
else:
print(f'Local Time: {datetime.datetime.now()}')
print(f'UTC time: {datetime.datetime.utcnow()}')
try:
baby = l[wich]
timezone = pytz.timezone(str(baby)) # convert to string value
time = datetime.datetime.now(tz=timezone)
print(f'{l[wich]} time: {time}')
except IndexError:
print('SORRY! WE DIDN´T FIND IT!')
for c in l:
print(c)
output
----------------------------------------------------------------------------------------------------------------------------
MENU
----------------------------------------------------------------------------------------------------------------------------
['0', 'Asia/Dubai', 'America/Yellowknife', 'Asia/Seoul', 'America/Denver', 'Pacific/Auckland', 'Europe/Oslo', 'Europe/Dublin', 'Europe/Amsterdam', 'Europe/Zurich']
Cod Country Timezone
1 United Arab Emirates Asia/Dubai
2 Canada America/Yellowknife
3 South Korea Asia/Seoul
4 United States America/Denver
5 New Zeland Pacific/Auckland
6 Norway Europe/Oslo
7 Ireland Europe/Dublin
8 Netherlands Europe/Amsterdam
9 Switzerland Europe/Zurich
----------------------------------------------------------------------------------------------------------------------------
Wich one? 1
Local Time: 2019-11-19 13:39:29.562076
UTC time: 2019-11-19 00:39:29.563094
Asia/Dubai time: 2019-11-19 04:39:29.564126+04:00
Wich one? 2
Local Time: 2019-11-19 13:39:31.849463
UTC time: 2019-11-19 00:39:31.849463
America/Yellowknife time: 2019-11-18 17:39:31.851457-07:00
Wich one? 3
Local Time: 2019-11-19 13:39:32.923009
UTC time: 2019-11-19 00:39:32.923009
Asia/Seoul time: 2019-11-19 09:39:32.924061+09:00
Wich one? 4
Local Time: 2019-11-19 13:39:33.977945
UTC time: 2019-11-19 00:39:33.978947
America/Denver time: 2019-11-18 17:39:33.979944-07:00
Wich one? 5
Local Time: 2019-11-19 13:39:34.849333
UTC time: 2019-11-19 00:39:34.850337
Pacific/Auckland time: 2019-11-19 13:39:34.851371+13:00
Wich one? 6
Local Time: 2019-11-19 13:39:35.570803
UTC time: 2019-11-19 00:39:35.570803
Europe/Oslo time: 2019-11-19 01:39:35.571802+01:00
Wich one? 7
Local Time: 2019-11-19 13:39:36.338700
UTC time: 2019-11-19 00:39:36.338700
Europe/Dublin time: 2019-11-19 00:39:36.341697+00:00
Wich one? 8
Local Time: 2019-11-19 13:39:37.234597
UTC time: 2019-11-19 00:39:37.234597
Europe/Amsterdam time: 2019-11-19 01:39:37.236625+01:00
Wich one? 9
Local Time: 2019-11-19 13:39:38.097607
UTC time: 2019-11-19 00:39:38.098611
Europe/Zurich time: 2019-11-19 01:39:38.099586+01:00
Wich one? 10
Local Time: 2019-11-19 13:39:43.267515
UTC time: 2019-11-19 00:39:43.267515
SORRY! WE DIDN´T FIND IT!
Wich one?

Flight Time encroaching any portion of a period python

I need to determine if a flight is a night flight or not. A flight has a departure time and an arrival time.
A nightflight is defined as a flight which encroaches any portion between 00:00 and 02:59.
I have 3 flights with their respective departure and arrival times:
16/01/2018 18:30 → 16/01/2018 20:25 which is not a night flight
16/01/2018 21:35 → 17/01/2018 01:15, which is a night flight
17/01/2018 23:30 → 18/01/2018 03:25, which is a night flight
There is the problem with following code:
def is_night_duty(self):
start_night = time(hour=0, minute=0, second=0)
end_night = time(hour=2, minute=59, second=59)
for flight in self.get_flights():
if start_night <= flight.departure().time.time() <= end_night or start_night<= flight.arrival().time.time() <= end_night:
return True
return False

Change Title Element in a List to Title Case in Python

f = open('database.txt','r')
data_set = ""
while 1:
line = f.readline()
if not line:break
data_set += line
print(data_set)
print()
I need to change the Title instances in the database to title case
Code so far, I will provide the list in the comments as I was having trouble adding to here
file = open("database.txt", 'r')
lines = file.readlines()
data_set = [line.split(' , ') for line in open ("database.txt")]
print (data_set)
for i in range(len(data_set[0])):
data_set[0][i]=s[i].t()
print(data_set)
converted the database to a list in the above code:[['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=court scene with cardinal richelieu\n'], ['ID=d45j5jkd\n'], ['Date=28 December 1969\n'], ['Title=THE ROYAL PHILHARMONIC ORCHESTRA GOES TO THE BATHROOM\n'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=crossing the atlantic on a tricycle\n'], ['ID=zd7u4h\n'], ['Date=19 October 1969\n'], ['Title=Bicycle Repair Man\n'], ['ID=f983\n'], ['Date=22 December 1970\n'], ['Title=Royal Episode 13 (or: The Queen Will Be Watching)\n'], ['ID=j8s74\n'], ['Date=15 September 1970\n'], ['Title=THE SEMAPHORE VERSION OF WUTHERING HEIGHTS\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither']]
iterate through the data_set and get texts after 'Title='and use str.title()!
data_set = [['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=court scene with cardinal richelieu\n'], ['ID=d45j5jkd\n'], ['Date=28 December 1969\n'], ['Title=THE ROYAL PHILHARMONIC ORCHESTRA GOES TO THE BATHROOM\n'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=crossing the atlantic on a tricycle\n'], ['ID=zd7u4h\n'], ['Date=19 October 1969\n'], ['Title=Bicycle Repair Man\n'], ['ID=f983\n'], ['Date=22 December 1970\n'], ['Title=Royal Episode 13 (or: The Queen Will Be Watching)\n'], ['ID=j8s74\n'], ['Date=15 September 1970\n'], ['Title=THE SEMAPHORE VERSION OF WUTHERING HEIGHTS\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither']]
for index,l in enumerate(data_set):
column_name,value = l[0].split("=")
if 'Title' == column_name:
data_set[index]="=".join([column_name+value.title()])
print data_set
data_set = [['ID=j234hg\n'], ['Date=19 October 1969\n'], ['Title=court scene with cardinal richelieu\n'], ['ID=d45j5jkd\n'], ['Date=28 December 1969\n'], ['Title=THE ROYAL PHILHARMONIC ORCHESTRA GOES TO THE BATHROOM\n'], ['ID=s4k5jk\n'], ['Date=8 December 1970\n'], ['Title=crossing the atlantic on a tricycle\n'], ['ID=zd7u4h\n'], ['Date=19 October 1969\n'], ['Title=Bicycle Repair Man\n'], ['ID=f983\n'], ['Date=22 December 1970\n'], ['Title=Royal Episode 13 (or: The Queen Will Be Watching)\n'], ['ID=j8s74\n'], ['Date=15 September 1970\n'], ['Title=THE SEMAPHORE VERSION OF WUTHERING HEIGHTS\n'], ['ID=n4j6l3j\n'], ['Date=7 December 1972\n'], ['Title=Mr. Pither']]
for index,l in enumerate(data_set):
if 'Title=' == l[0][:6]:
data_set[index]="Title="+l[0][6:].title()
print data_set

Python - From DST-adjusted local time to UTC

A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time.
What I need is a function to_utc(localdt, tz) like this:
Arguments:
localdt: localtime, as naive datetime object, DST-adjusted
tz: timezone in the TZ-format, e.g. 'Europe/Berlin'
Returns:
datetime object, in UTC, timezone-aware
EDIT:
The biggest challenge is to detect whether the local time is in a period with DST, which also means that it is DST adjusted.
For 'Europe/Berlin' which has +1 DST in the summer:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 8:00 UTC
For 'Africa/Lagos' which has no DST:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 9:00 UTC
Using pytz, and in particular its localize method:
import pytz
import datetime as dt
def to_utc(localdt,tz):
timezone=pytz.timezone(tz)
utc=pytz.utc
return timezone.localize(localdt).astimezone(utc)
if __name__=='__main__':
for tz in ('Europe/Berlin','Africa/Lagos'):
for date in (dt.datetime(2011,1,1,10,0,0),
dt.datetime(2011,7,1,10,0,0),
):
print('{tz:15} {l} --> {u}'.format(
tz=tz,
l=date.strftime('%b %d %H:%M'),
u=to_utc(date,tz).strftime('%b %d %H:%M %Z')))
yields
Europe/Berlin Jan 01 10:00 --> Jan 01 09:00 UTC
Europe/Berlin Jul 01 10:00 --> Jul 01 08:00 UTC
Africa/Lagos Jan 01 10:00 --> Jan 01 09:00 UTC
Africa/Lagos Jul 01 10:00 --> Jul 01 09:00 UTC
from datetime import datetime, tzinfo, timedelta
class GMT1(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=1)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "Europe/Prague"
year, month, day = 2011, 7, 23
dt = datetime(year, month, day, 10)
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "UTC"
def utc(localt, tz):
return localt.replace(tzinfo=tz).astimezone(UTC())
print utc(dt, GMT1())
New Version. This does what you want -- takes a naive datetime and a timezone and returns a UTC datetime.

Categories

Resources