import pytz
from datetime import datetime
def list_timezones():
timezones = pytz.common_timezones
for index, tz in enumerate(timezones):
print(f"{index + 1}. {tz}")
def convert_timezone(from_tz, to_tz, time_str):
try:
from_timezone = pytz.timezone(from_tz)
to_timezone = pytz.timezone(to_tz)
# Parse the input time string into a datetime object
input_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
# Convert the input time from the 'from_tz' timezone to the 'to_tz' timezone
converted_time = input_time.replace(tzinfo=from_timezone).astimezone(to_timezone)
return converted_time.strftime("%Y-%m-%d %H:%M:%S %Z")
except Exception as e:
return str(e)
if __name__ == "__main__":
print("Welcome to the Time Zone Converter!")
print("List of available time zones:")
list_timezones()
from_tz = input("Enter the source time zone (e.g., 'America/New_York'): ")
to_tz = input("Enter the target time zone (e.g., 'Europe/London'): ")
time_str = input("Enter a date and time in the format 'YYYY-MM-DD HH:MM:SS': ")
converted_time = convert_timezone(from_tz, to_tz, time_str)
if converted_time:
print(f"Converted time: {converted_time}")
else:
print("Invalid input or time zone not found.")
Welcome to the Time Zone Converter!
List of available time zones:
1. Africa/Abidjan
2. Africa/Accra
3. Africa/Addis_Ababa
4. Africa/Algiers
5. Africa/Asmara
6. Africa/Bamako
7. Africa/Bangui
8. Africa/Banjul
9. Africa/Bissau
10. Africa/Blantyre
11. Africa/Brazzaville
12. Africa/Bujumbura
13. Africa/Cairo
14. Africa/Casablanca
15. Africa/Ceuta
16. Africa/Conakry
17. Africa/Dakar
18. Africa/Dar_es_Salaam
19. Africa/Djibouti
20. Africa/Douala
21. Africa/El_Aaiun
22. Africa/Freetown
23. Africa/Gaborone
24. Africa/Harare
25. Africa/Johannesburg
26. Africa/Juba
27. Africa/Kampala
28. Africa/Khartoum
29. Africa/Kigali
30. Africa/Kinshasa
31. Africa/Lagos
32. Africa/Libreville
33. Africa/Lome
34. Africa/Luanda
35. Africa/Lubumbashi
36. Africa/Lusaka
37. Africa/Malabo
38. Africa/Maputo
39. Africa/Maseru
40. Africa/Mbabane
41. Africa/Mogadishu
42. Africa/Monrovia
43. Africa/Nairobi
44. Africa/Ndjamena
45. Africa/Niamey
46. Africa/Nouakchott
47. Africa/Ouagadougou
48. Africa/Porto-Novo
49. Africa/Sao_Tome
50. Africa/Tripoli
51. Africa/Tunis
52. Africa/Windhoek
53. America/Adak
54. America/Anchorage
55. America/Anguilla
56. America/Antigua
57. America/Araguaina
58. America/Argentina/Buenos_Aires
59. America/Argentina/Catamarca
60. America/Argentina/Cordoba
61. America/Argentina/Jujuy
62. America/Argentina/La_Rioja
63. America/Argentina/Mendoza
64. America/Argentina/Rio_Gallegos
65. America/Argentina/Salta
66. America/Argentina/San_Juan
67. America/Argentina/San_Luis
68. America/Argentina/Tucuman
69. America/Argentina/Ushuaia
70. America/Aruba
71. America/Asuncion
72. America/Atikokan
73. America/Bahia
74. America/Bahia_Banderas
75. America/Barbados
76. America/Belem
77. America/Belize
78. America/Blanc-Sablon
79. America/Boa_Vista
80. America/Bogota
81. America/Boise
82. America/Cambridge_Bay
83. America/Campo_Grande
84. America/Cancun
85. America/Caracas
86. America/Cayenne
87. America/Cayman
88. America/Chicago
89. America/Chihuahua
90. America/Ciudad_Juarez
91. America/Costa_Rica
92. America/Creston
93. America/Cuiaba
94. America/Curacao
95. America/Danmarkshavn
96. America/Dawson
97. America/Dawson_Creek
98. America/Denver
99. America/Detroit
100. America/Dominica
101. America/Edmonton
102. America/Eirunepe
103. America/El_Salvador
104. America/Fort_Nelson
105. America/Fortaleza
106. America/Glace_Bay
107. America/Goose_Bay
108. America/Grand_Turk
109. America/Grenada
110. America/Guadeloupe
111. America/Guatemala
112. America/Guayaquil
113. America/Guyana
114. America/Halifax
115. America/Havana
116. America/Hermosillo
117. America/Indiana/Indianapolis
118. America/Indiana/Knox
119. America/Indiana/Marengo
120. America/Indiana/Petersburg
121. America/Indiana/Tell_City
122. America/Indiana/Vevay
123. America/Indiana/Vincennes
124. America/Indiana/Winamac
125. America/Inuvik
126. America/Iqaluit
127. America/Jamaica
128. America/Juneau
129. America/Kentucky/Louisville
130. America/Kentucky/Monticello
131. America/Kralendijk
132. America/La_Paz
133. America/Lima
134. America/Los_Angeles
135. America/Lower_Princes
136. America/Maceio
137. America/Managua
138. America/Manaus
139. America/Marigot
140. America/Martinique
141. America/Matamoros
142. America/Mazatlan
143. America/Menominee
144. America/Merida
145. America/Metlakatla
146. America/Mexico_City
147. America/Miquelon
148. America/Moncton
149. America/Monterrey
150. America/Montevideo
151. America/Montserrat
152. America/Nassau
153. America/New_York
154. America/Nome
155. America/Noronha
156. America/North_Dakota/Beulah
157. America/North_Dakota/Center
158. America/North_Dakota/New_Salem
159. America/Nuuk
160. America/Ojinaga
161. America/Panama
162. America/Paramaribo
163. America/Phoenix
164. America/Port-au-Prince
165. America/Port_of_Spain
166. America/Porto_Velho
167. America/Puerto_Rico
168. America/Punta_Arenas
169. America/Rankin_Inlet
170. America/Recife
171. America/Regina
172. America/Resolute
173. America/Rio_Branco
174. America/Santarem
175. America/Santiago
176. America/Santo_Domingo
177. America/Sao_Paulo
178. America/Scoresbysund
179. America/Sitka
180. America/St_Barthelemy
181. America/St_Johns
182. America/St_Kitts
183. America/St_Lucia
184. America/St_Thomas
185. America/St_Vincent
186. America/Swift_Current
187. America/Tegucigalpa
188. America/Thule
189. America/Tijuana
190. America/Toronto
191. America/Tortola
192. America/Vancouver
193. America/Whitehorse
194. America/Winnipeg
195. America/Yakutat
196. Antarctica/Casey
197. Antarctica/Davis
198. Antarctica/DumontDUrville
199. Antarctica/Macquarie
200. Antarctica/Mawson
201. Antarctica/McMurdo
202. Antarctica/Palmer
203. Antarctica/Rothera
204. Antarctica/Syowa
205. Antarctica/Troll
206. Antarctica/Vostok
207. Arctic/Longyearbyen
208. Asia/Aden
209. Asia/Almaty
210. Asia/Amman
211. Asia/Anadyr
212. Asia/Aqtau
213. Asia/Aqtobe
214. Asia/Ashgabat
215. Asia/Atyrau
216. Asia/Baghdad
217. Asia/Bahrain
218. Asia/Baku
219. Asia/Bangkok
220. Asia/Barnaul
221. Asia/Beirut
222. Asia/Bishkek
223. Asia/Brunei
224. Asia/Chita
225. Asia/Choibalsan
226. Asia/Colombo
227. Asia/Damascus
228. Asia/Dhaka
229. Asia/Dili
230. Asia/Dubai
231. Asia/Dushanbe
232. Asia/Famagusta
233. Asia/Gaza
234. Asia/Hebron
235. Asia/Ho_Chi_Minh
236. Asia/Hong_Kong
237. Asia/Hovd
238. Asia/Irkutsk
239. Asia/Jakarta
240. Asia/Jayapura
241. Asia/Jerusalem
242. Asia/Kabul
243. Asia/Kamchatka
244. Asia/Karachi
245. Asia/Kathmandu
246. Asia/Khandyga
247. Asia/Kolkata
248. Asia/Krasnoyarsk
249. Asia/Kuala_Lumpur
250. Asia/Kuching
251. Asia/Kuwait
252. Asia/Macau
253. Asia/Magadan
254. Asia/Makassar
255. Asia/Manila
256. Asia/Muscat
257. Asia/Nicosia
258. Asia/Novokuznetsk
259. Asia/Novosibirsk
260. Asia/Omsk
261. Asia/Oral
262. Asia/Phnom_Penh
263. Asia/Pontianak
264. Asia/Pyongyang
265. Asia/Qatar
266. Asia/Qostanay
267. Asia/Qyzylorda
268. Asia/Riyadh
269. Asia/Sakhalin
270. Asia/Samarkand
271. Asia/Seoul
272. Asia/Shanghai
273. Asia/Singapore
274. Asia/Srednekolymsk
275. Asia/Taipei
276. Asia/Tashkent
277. Asia/Tbilisi
278. Asia/Tehran
279. Asia/Thimphu
280. Asia/Tokyo
281. Asia/Tomsk
282. Asia/Ulaanbaatar
283. Asia/Urumqi
284. Asia/Ust-Nera
285. Asia/Vientiane
286. Asia/Vladivostok
287. Asia/Yakutsk
288. Asia/Yangon
289. Asia/Yekaterinburg
290. Asia/Yerevan
291. Atlantic/Azores
292. Atlantic/Bermuda
293. Atlantic/Canary
294. Atlantic/Cape_Verde
295. Atlantic/Faroe
296. Atlantic/Madeira
297. Atlantic/Reykjavik
298. Atlantic/South_Georgia
299. Atlantic/St_Helena
300. Atlantic/Stanley
301. Australia/Adelaide
302. Australia/Brisbane
303. Australia/Broken_Hill
304. Australia/Darwin
305. Australia/Eucla
306. Australia/Hobart
307. Australia/Lindeman
308. Australia/Lord_Howe
309. Australia/Melbourne
310. Australia/Perth
311. Australia/Sydney
312. Canada/Atlantic
313. Canada/Central
314. Canada/Eastern
315. Canada/Mountain
316. Canada/Newfoundland
317. Canada/Pacific
318. Europe/Amsterdam
319. Europe/Andorra
320. Europe/Astrakhan
321. Europe/Athens
322. Europe/Belgrade
323. Europe/Berlin
324. Europe/Bratislava
325. Europe/Brussels
326. Europe/Bucharest
327. Europe/Budapest
328. Europe/Busingen
329. Europe/Chisinau
330. Europe/Copenhagen
331. Europe/Dublin
332. Europe/Gibraltar
333. Europe/Guernsey
334. Europe/Helsinki
335. Europe/Isle_of_Man
336. Europe/Istanbul
337. Europe/Jersey
338. Europe/Kaliningrad
339. Europe/Kirov
340. Europe/Kyiv
341. Europe/Lisbon
342. Europe/Ljubljana
343. Europe/London
344. Europe/Luxembourg
345. Europe/Madrid
346. Europe/Malta
347. Europe/Mariehamn
348. Europe/Minsk
349. Europe/Monaco
350. Europe/Moscow
351. Europe/Oslo
352. Europe/Paris
353. Europe/Podgorica
354. Europe/Prague
355. Europe/Riga
356. Europe/Rome
357. Europe/Samara
358. Europe/San_Marino
359. Europe/Sarajevo
360. Europe/Saratov
361. Europe/Simferopol
362. Europe/Skopje
363. Europe/Sofia
364. Europe/Stockholm
365. Europe/Tallinn
366. Europe/Tirane
367. Europe/Ulyanovsk
368. Europe/Vaduz
369. Europe/Vatican
370. Europe/Vienna
371. Europe/Vilnius
372. Europe/Volgograd
373. Europe/Warsaw
374. Europe/Zagreb
375. Europe/Zurich
376. GMT
377. Indian/Antananarivo
378. Indian/Chagos
379. Indian/Christmas
380. Indian/Cocos
381. Indian/Comoro
382. Indian/Kerguelen
383. Indian/Mahe
384. Indian/Maldives
385. Indian/Mauritius
386. Indian/Mayotte
387. Indian/Reunion
388. Pacific/Apia
389. Pacific/Auckland
390. Pacific/Bougainville
391. Pacific/Chatham
392. Pacific/Chuuk
393. Pacific/Easter
394. Pacific/Efate
395. Pacific/Fakaofo
396. Pacific/Fiji
397. Pacific/Funafuti
398. Pacific/Galapagos
399. Pacific/Gambier
400. Pacific/Guadalcanal
401. Pacific/Guam
402. Pacific/Honolulu
403. Pacific/Kanton
404. Pacific/Kiritimati
405. Pacific/Kosrae
406. Pacific/Kwajalein
407. Pacific/Majuro
408. Pacific/Marquesas
409. Pacific/Midway
410. Pacific/Nauru
411. Pacific/Niue
412. Pacific/Norfolk
413. Pacific/Noumea
414. Pacific/Pago_Pago
415. Pacific/Palau
416. Pacific/Pitcairn
417. Pacific/Pohnpei
418. Pacific/Port_Moresby
419. Pacific/Rarotonga
420. Pacific/Saipan
421. Pacific/Tahiti
422. Pacific/Tarawa
423. Pacific/Tongatapu
424. Pacific/Wake
425. Pacific/Wallis
426. US/Alaska
427. US/Arizona
428. US/Central
429. US/Eastern
430. US/Hawaii
431. US/Mountain
432. US/Pacific
433. UTC
Enter the source time zone (e.g., 'America/New_York'): Asia/Bahrain
Enter the target time zone (e.g., 'Europe/London'): Australia/Sydney
Enter a date and time in the format 'YYYY-MM-DD HH:MM:SS': 2023-09-11 00:38:00
Converted time: 2023-09-11 07:12:00 AEST
feedback from chatgpt
-
Your code is well-structured and functional for its intended purpose, but here are a few additional suggestions for improvement:
-
User-Friendly Input Handling: While your code handles exceptions, it might be more user-friendly to provide specific error messages to the user for common input mistakes. For example, if the user enters an invalid time zone name or an incorrectly formatted date-time string, you can guide them on the expected format or suggest valid time zone names.
-
User Experience: Consider adding a loop that continuously prompts the user for input until they provide valid inputs or choose to exit the program. This would enhance the user experience and reduce the chances of invalid inputs.
-
Handling Time Zone Abbreviations: The code currently displays the time zone abbreviation (e.g., ‘EST’, ‘BST’) in the converted time. While this can be informative, it’s important to note that time zone abbreviations are not unique and can be ambiguous. For more accurate results, you may want to display the full time zone name (e.g., ‘Eastern Standard Time’, ‘British Summer Time’).
-
Time Zone Autocompletion: For a better user experience, you could implement a mechanism that suggests or autocompletes time zone names as the user starts typing, making it easier to select the correct time zone.
-
Error Handling Improvement: Instead of returning the exception message as a string in the convert_timezone function, it might be better to raise a custom exception with a meaningful error message. This way, you can provide specific error information to the caller, and it makes it easier to handle different types of errors separately.
-
Documentation: Consider adding docstrings to your functions to explain their purpose and expected inputs/outputs. Additionally, you can add comments within the code to clarify specific parts of the logic.
code explained
-
list_timezones(): This function lists all the common time zones available in the “pytz” library. It loops through the list of time zones and prints them with an index number.
-
convert_timezone(from_tz, to_tz, time_str): This function takes three inputs: the source time zone, the target time zone, and a date/time string. It attempts to convert the given date/time from the source time zone to the target time zone. If successful, it returns the converted date/time as a string in the format “YYYY-MM-DD HH:MM:SS TZ” (with TZ representing the time zone abbreviation). If any error occurs during the conversion, it returns an error message as a string.
-
The code inside the if name == “main”: block runs when the script is executed directly. It starts by printing a welcome message and listing the available time zones using the list_timezones() function.
-
It then prompts the user to enter the source time zone (e.g., ‘America/New_York’), the target time zone (e.g., ‘Europe/London’), and a date/time string in the format ‘YYYY-MM-DD HH:MM:SS’.
-
The convert_timezone function is called with the user’s inputs to perform the time zone conversion. If the conversion is successful, it prints the converted time; otherwise, it prints an error message.