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?
Related
I have this function for checking a specific time and day in the week.
It should print 1 from Sunday 7:00PM to Friday 8:00PM
And print 0 from Friday 8:00PM to Sunday 7:00PM
I checked the function on Friday around 11:00AM and 2:00PM and I'm getting the error message in the title.
Can someone explain exactly what the error means? And how I could maybe fix it? It's supposed to check the time in Eastern Standard Time always
import pytz
from datetime import datetime, time, date
est = pytz.timezone('EST')
Mon = 0
Tue = 1
Wed = 2
Thur = 3
Fri = 4
Sat = 5
Sun = 6
weekdays = [Mon, Tue, Wed, Thur]
edgecases = [Sun, Fri]
weekend = [Sat]
curr_day = datetime.now(tz=est).date().weekday()
curr_time = datetime.now(tz=est).time()
def checktime(curr_day, curr_time):
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
print(1)
elif curr_day in weekend or (curr_day == Fri and curr_time >= time(20,00,tzinfo=est)) or (curr_day == Sun and curr_time <= time(19,00,tzinfo=est)):
print(0)
Traceback error:
Traceback (most recent call last):
File ".\testingtime.py", line 73, in <module>
checktime(curr_day, curr_time)
File ".\testingtime.py", line 67, in checktime
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00,tzinfo=est)) or (curr_day == Fri and curr_time < time(20,00,tzinfo=est)):
TypeError: can't compare offset-naive and offset-aware times
For one, if you call the time() method on a tz aware datetime object, the resulting time object will not carry the timezone info anymore - since it is assumed that it makes no sense without the date. Second, since you compare to static times, you don't need a timezone there. You can thus simplify your function to
def checktime(curr_day, curr_time):
if curr_day in weekdays or (curr_day == Sun and curr_time > time(19,00)) or (curr_day == Fri and curr_time < time(20,00)):
print(1)
elif curr_day in weekend or (curr_day == Fri and curr_time >= time(20,00)) or (curr_day == Sun and curr_time <= time(19,00)):
print(0)
This sorted it for me:
dt_obj = dt_obj.replace(tzinfo=None)
See python – Can’t subtract offset-naive and offset-aware datetimes ... answer 1
I have problem with the for loop in Python. I want to sum these data based on time and location, without pandas. This data is in the MySQL database (mysql workbench):
Time No_of_people Location
----------------------------------------
07:00 20 Liberty City
07:15 25 Liberty City
07:30 20 Liberty City
07:45 30 Liberty City
08:00 21 Liberty City
...
07:00 10 San Andreas
07:15 15 San Andreas
07:30 20 San Andreas
07:45 25 San Andreas
08:00 30 San Andreas
Now I want it to be like:
Time No_of_people Location
----------------------------------------
07:00 116 Liberty City
08:00 120 Liberty City
...
07:00 100 San Andreas
This is currently what I have done:
views.py:
def getData(request):
api = 'http://localhost:8000/api/myData/'
response = requests.get(api)
myData = response.json()
time = []
no_of_people = []
location = []
for hourly in myData:
time.append(hourly['time'])
no_of_people.append(hourly['no_of_people'])
location.append(hourly['location'])
hour = []
for x in range(7,24):
hour.append(x)
uniqueLocation=[]
for x in location:
if x not in uniqueLocation:
uniqueLocation.append(x)
for uniqueIndex in uniqueLocation:
for x in hour:
sum =0
for index, t in enumerate(time):
x_time = t.split(":")[0]
if int(x_time) == x and uniqueIndex == location[index]:
sum += no_of_people[index]
print(str(sum))
json_obj = {
"time": time,
"no_of_people": no_of_people,
"location": location
}
return JsonResponse(data=json_obj)
You want to group by the location, therefore I suggest you aim for this format, which is easier to visualize, and then try to build the table output from there (for each city, for each time, print hour and people/hr)
[
{'location' : 'Liberty City', 'times': [{'hour' : '7:00', 'people' : 116}, ...]},
...
]
When working with almost any database, try to create a class per object (row, table, bucket, relationship, (insert database term here), etc). You can then isolate logic here rather than clutter the main function
class Location:
def __init__(self, name):
self.name = name
self.times = list()
def __str__(self):
s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()]
return '\n'.join(s)
def add_time(self, hour, people):
existing_people_for_hour = None
for t in self.times: # loop existing times, looking for the hour
existing_people_for_hour = t.get(hour)
if existing_people_for_hour is not None:
t[hour] += people
break # found the hour to update, so break the loop
if existing_people_for_hour is None: # if the hour was never found, add to the times list
self.times.append({hour : people})
With that in place, use a dictionary to group on the location value and you should be able to print them in the end
locations = dict()
for d in myData:
# parse each value out
hour = d['time'][:2] + ':00'
p = int(d['no_of_people'])
loc = d['location']
# get the location from the map, if exists, else create new one
l = locations.get(loc, Location(loc))
l.add_time(hour, p) # add the people for the time
locations[loc] = l # upsert the new location
for l in locations.values():
print(l)
Output
07:00 95 Liberty City
08:00 21 Liberty City
07:00 70 San Andreas
08:00 30 San Andreas
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
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
import os, sys
import os.path, time
path=os.getcwd()
def file_info(directory):
file_list = []
for i in os.listdir(directory):
a = os.stat(os.path.join(directory,i))
file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
return file_list
print file_info(path)
Problem
how I can show each list item in new line and nice a nice format
how I can sort the file/directory list based on last modified
how I can sort the file/directory list based on creatation date
Here is the program with some nice printing using the format function:
import os
import time
path = os.getcwd()
def file_info(directory):
file_list = []
for i in os.listdir(directory):
a = os.stat(os.path.join(directory,i))
file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
return file_list
file_list = file_info(path)
for item in file_list:
line = "Name: {:<20} | Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
print(line)
Here is some code with a sort function being used on the accessed time. The code is not optimized but it is very readable and you should be able to understand it.
import os
import time
path = os.getcwd()
def file_info(directory,sortLastModifiedOrNaw=False):
file_list = []
currentMin = 0 #This is the variable that will track the lowest digit
for i in os.listdir(directory):
a = os.stat(os.path.join(directory,i))
if sortLastModifiedOrNaw == True: #If you would like to sort.
if a.st_atime > currentMin: #Check if this is bigger than the current minimum.
currentMin = a.st_atime #If it is we update the current minimum
#Below we append so that it ends up in the end of the list
file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
else: #If it is smaller, it should be in the front of the list so we insert it into position 0.
file_list.insert(0,[i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
else: #If you would not like to sort
file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
return file_list
file_list = file_info(path)
print("Unsorted Example")
for item in file_list:
line = "Name: {:<20} | Date Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
print(line)
print("\nSorted example using last modified time")
file_list = file_info(path,sortLastModifiedOrNaw=True)
for item in file_list:
line = "Name: {:<20} | Date Last Accessed: {:>20} | Date Created: {:>20}".format(item[0],item[1],item[2])
print(line)
Sample output:
Unsorted Example
Name: .idea | Date Last Accessed: Sun Jan 3 21:13:45 2016 | Date Created: Sun Jan 3 21:13:14 2016
Name: blahblah.py | Date Last Accessed: Sun Jan 3 21:13:48 2016 | Date Created: Sun Jan 3 21:13:48 2016
Name: testhoe1.py | Date Last Accessed: Sun Jan 3 19:09:57 2016 | Date Created: Sun Jan 3 18:52:06 2016
Sorted example using last modified time
Name: testhoe1.py | Date Last Accessed: Sun Jan 3 19:09:57 2016 | Date Created: Sun Jan 3 18:52:06 2016
Name: .idea | Date Last Accessed: Sun Jan 3 21:13:45 2016 | Date Created: Sun Jan 3 21:13:14 2016
Name: blahblah.py | Date Last Accessed: Sun Jan 3 21:13:48 2016 | Date Created: Sun Jan 3 21:13:48 2016
Happy optimizing! #If you change line 12 atime to ctime it will sort based on create-time.