Adding city name in front of branch datetimes - python

I have three branch locations with the times in respect to their cities, however, I don't know how to write the names of the cities in front of the times. Would someone please help me?
Thanks
from datetime import datetime
from pytz import timezone
import pytz
portland_time = datetime.now(tz=pytz.UTC).replace(microsecond=0)
Portland = portland_time.astimezone(pytz.timezone('US/Pacific'))
new_york_time = portland_time.astimezone(timezone('US/Eastern'))
Ny = new_york_time
london_time = portland_time.astimezone(timezone('Europe/London'))
London = london_time
cities = {'Portland': Portland,
'Ny': Ny,
'London': London}
def branches():
for city in cities:
Branchtime=int(cities[city].strftime('%H'))
if Branchtime >= 9 and Branchtime < 21:
print(city, cities[city], 'OPEN')
else:
print(city, cities[city], 'CLOSED')
branches()

Do you mind using a dict instead of a list for your cities? If not you can do this:
from datetime import datetime
from pytz import timezone
import pytz
portland_time = datetime.now(tz=pytz.UTC).replace(microsecond=0)
Portland = portland_time.astimezone(pytz.timezone('US/Pacific'))
new_york_time = portland_time.astimezone(timezone('US/Eastern'))
Ny = new_york_time
london_time = portland_time.astimezone(timezone('Europe/London'))
London = london_time
cities = {'Portland': Portland,
'Ny': Ny,
'London': London}
for city in cities:
Branchtime=int(cities[city].strftime('%H'))
if Branchtime >= 9 and Branchtime < 21:
print(city, cities[city], 'OPEN')
else:
print(city, cities[city], 'CLOSED')
Gives you:
Ny 2017-06-10 02:22:55-04:00 CLOSED
Portland 2017-06-09 23:22:55-07:00 CLOSED
London 2017-06-10 07:22:55+01:00 CLOSED

Related

how to convert windows system timezone to uk timezone

i'm trying to convert "(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time" to uk timzone. I found the solution using this "Asia/Kolkata" but I should either pass "(UTC+05:30)" or "Chennai, Kolkata, Mumbai, New Delhi" or "India Standard Time" to my function to convert it into uk time.
Here is my code:
from datetime import datetime
from pytz import timezone
def get_uk_time(time_zone):
try:
country_tz = timezone(time_zone)
format = "%Y, %m, %d, %H, %M, %S"
time_now = datetime.now(timezone(time_zone))
format_time = time_now.strftime(format)
london_tz = timezone('Europe/London')
local_time = country_tz.localize(datetime.strptime(format_time, format))
convert_to_london_time = local_time.astimezone(london_tz)
uk_time = convert_to_london_time.strftime('%H:%M')
return uk_time
except:
print('unable to find the timezone')
#my_json = {'timezone': 'Asia/Kolkata'}
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}
time_zone = my_json['timezone']
time_in_london = get_uk_time(time_zone)
print(time_in_london)
If we remove the try/except, the error is :
File "/home/stack_overflow/so71012475.py", line 6, in get_uk_time
country_tz = timezone(time_zone)
pytz.exceptions.UnknownTimeZoneError: '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'
Because (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time is not a correct identifier. I could not find which identifiers it corresponds to, but I can suggest another approach.
Because you know the UTC offset, you can create a timezone object with it, and use it to compute the UK time :
import datetime
import re
import pytz
# the data you provided
my_json = {'timezone': '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi India Standard Time'}
# a regex to extract relevant info from your data
pattern = re.compile(r"\(UTC(?P<sign>[+-])(?P<hours>\d\d):(?P<minutes>\d\d)\)(?P<name>.*)")
# extract the info
match = pattern.match(my_json["timezone"])
assert match is not None
tz_name = match.group("name").strip()
hours, minutes = int(match.group("hours")), int(match.group("minutes"))
is_negative = match.group("sign") == "-"
# build the timezone object
my_tz = datetime.timezone(offset=datetime.timedelta(hours=hours, minutes=minutes), name=tz_name)
if is_negative:
my_tz = -my_tz
# use the timezone object to localize the current time
my_time = datetime.datetime.now().replace(tzinfo=my_tz)
print(my_time)
# and convert it to UK time
uk_tz = pytz.timezone('Europe/London')
uk_time = my_time.astimezone(uk_tz)
print(uk_time)
2022-02-07 14:33:12.463372+05:30
2022-02-07 09:03:12.463372+00:00
(it is actually 14:30 at my local time when I am writing this answer, and if I was in India, it would mean that it is 09:00 in London.

Not able to figure how to write if-else statement for one of the user defined cases in python

I have two API.
Australia API- This API works only for year 1985 to 2024.
USA API- I wanted this API need should work only before 1985.
Taking 4 things from user.
-Start Year
-End Year
-latitude
-longitude
sample command: python test.py -latitude '' -longitude '' -startYear '' -endYear ''
User can enter 3 ways of input.
Case 1. Start year=before 1985, end year= After 1985 ---->both AUSTRALIA and USA api run.
Case 2. Start year=At 1985 or later, end year= after 1985 ---->only AUSTRALIA api should run.
Case 3. Start year=before 1985, end year=before 1985 ------>only USA api run
Problem is that I am not able to figure out how to write the code for Case 1 after writing the code for case 2(Australia API) and case 3(USA API).
import requests
import json
import argparse
import time
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("-latitude", help="Latitude(Degress)")
parser.add_argument("-longitude", help="Longitude(Degress)")
parser.add_argument("-startYear", help="Start of the Year")
parser.add_argument("-endYear", help="End of the Year")
parser.add_argument("--verbose", help="display processing information")
start = time.time()
def main(latitude,longitude,startYear,endYear,verbose):
parameters = {
"latd": latitude, # [deg]
"latm": 00, # [deg]
"lats": 00, # [deg]
"lond": longitude, # [deg]
"lonm": 00, # [deg]
"lons": 00, # [deg]
"elev" : 00, # [km]
"year" : None, # [YYYY]
"month" : '07', # [MM]
"day": '01', # [DD]
"Ein": 'D' # [Model]
}
hostname = "https://api.geomagnetism.ga.gov.au/agrf"
hostname1 = "http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?%s"
df_1=pd.DataFrame()
for year in range(startYear, endYear):
if (startYear>=1985 and endYear>1985):
-----
elif (startYear<1985 and endYear<1985):
-------
if endYear < 1985:
if startYear < 1985:
# Case 3
elif startYear >= 1985:
# Case 2
elif startYear < 1985:
# Case 1
else:
# Case where endYear < 1985 and startYear > 1985 (probably an input error)
if end > 1985:
australia
if start < 1985:
usa
else:
usa

Python float print in real time

Is there any way to print the numbers in real times instead of printing them one by one? I have 6 different countries
china = 1399746872
india = 1368138206
USA = 327826334
Japan = 12649000
Russia = 146804372
Sweden = 10379295
I change this numbers in the script but how do I print them so I see them change?
!EDITED!
I want to kind of overwrite this list everytime it prints so I see the numbers go up
Countries = []
china = 1399746872
india = 1368138206
USA = 327826334
Japan = 12649000
Russia = 146804372
Sweden = 10379295
Countries.append(china)
Countries.append(india)
Countries.append(USA)
Countries.append(Japan)
Countries.append(Russia)
Countries.append(Sweden)
print(Countries)
you could use os.system("cls") to clear the console.
I made a little demo:
import time, sys, json, os
from random import randint
vals = {
"china": 1399746872,
"india": 1368138206,
"USA": 327826334,
"Japan": 12649000,
"Russia": 146804372,
"Sweden": 10379295
}
for _ in range(100):
# clear console
os.system("cls")
# print values
[print(f"{k}: {v}") for k, v in vals.items()]
# renew values with random generated integers
vals = {k:randint(0, 1000000) for k in vals}
# sleep 5s
time.sleep(5)

Python for dummies using the bakeshare data

I want to run this code but I have some errors and I can't see the problem. The code is below. And do I have to set global list for cities, month and the day?
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = get_user_input('Now you have to enter a month to get some months result) \n> ', months)
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]
day = get_user_input('Now you have to enter a month to get some months result) \n> ', days)
print('-'*40)
return city, month, day
If I understood you correctly I think this is what you have to do:
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').capitalize() #was lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = input('Now you have to enter a month to get some months result \n> {} \n> '.format(months))
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = input('Now you have to enter a dau to get some days result \n> {} \n> '.format(days))
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
A couple of things to note:
The input of the city was set to '.lower()' while the list of cities contained capitilized letters. So I changed it to capitilize().
Also you wanted it to return every day and month if the user didn't specify any input. Therefore I added a simple if-test at the end to check for that. Furthermore I used the '-format()' to display the different options the user has on the input. Hope everything is clear!
Using .lower() is fine, but you should change your cities list and your `CITY_DATA`` dict to match the names (so New York City --: new york).
CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('chicago', 'new york', 'washington')
while True:
city = raw_input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = raw_input('Now you have to enter a month to get some months result \n> {} \n>'.format(months)).lower()
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = raw_input('Now you have to enter a day to get some days result \n> {} \n>'.format(days)).lower()
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
If you are using Python 2.7, you should use raw_input() instead of input().

Python regex to capture a comma-delimited list of items

I have a list of weather forecasts that start with a similar prefix that I'd like to remove. I'd also like to capture the city names:
Some Examples:
If you have vacation or wedding plans in Phoenix, Tucson, Flagstaff,
Salt Lake City, Park City, Denver, Estes Park, Colorado Springs,
Pueblo, or Albuquerque, the week will...
If you have vacation or wedding plans for Miami, Jacksonville, Macon,
Charlotte, or Charleston, expect a couple systems...
If you have vacation or wedding plans in Pittsburgh, Philadelphia,
Atlantic City, Newark, Baltimore, D.C., Richmond, Charleston, or
Dover, expect the week...
The strings start with a common prefix "If you have vacation or wedding plans in" and the last city has "or" before it. The list of cities is of variable length.
I've tried this:
>>> text = 'If you have vacation or wedding plans in NYC, Boston, Manchester, Concord, Providence, or Portland'
>>> re.search(r'^If you have vacation or wedding plans in ((\b\w+\b), ?)+ or (\w+)', text).groups()
('Providence,', 'Providence', 'Portland')
>>>
I think I'm pretty close, but obviously it's not working. I've never tried to do something with a variable number of captured items; any guidance would be greatly appreciated.
Alternative solution here (probably just for sharing and educational purposes).
If you were to solve it with nltk, it would be called a Named Entity Recognition problem. Using the snippet based on nltk.chunk.ne_chunk_sents(), provided here:
import nltk
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'label') and t.label:
if t.label() == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
sample = "If you have vacation or wedding plans in Phoenix, Tucson, Flagstaff, Salt Lake City, Park City, Denver, Estes Park, Colorado Springs, Pueblo, or Albuquerque, the week will..."
sentences = nltk.sent_tokenize(sample)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.ne_chunk_sents(tagged_sentences, binary=True)
entity_names = []
for tree in chunked_sentences:
entity_names.extend(extract_entity_names(tree))
print entity_names
It prints exactly the desired result:
['Phoenix', 'Tucson', 'Flagstaff', 'Salt Lake City', 'Park City', 'Denver', 'Estes Park', 'Colorado Springs', 'Pueblo', 'Albuquerque']
Here is my approach: use the csv module to parse the lines (I assume they are in a text file named data.csv, please change to suite your situation). After parsing each line:
Discard the last cell, it is not a city name
Remove 'If ...' from the first cell
Remove or 'or ' from the last cell (used to be next-to-last)
Here is the code:
import csv
def cleanup(row):
new_row = row[:-1]
new_row[0] = new_row[0].replace('If you have vacation or wedding plans in ', '')
new_row[0] = new_row[0].replace('If you have vacation or wedding plans for ', '')
new_row[-1] = new_row[-1].replace('or ', '')
return new_row
if __name__ == '__main__':
with open('data.csv') as f:
reader = csv.reader(f, skipinitialspace=True)
for row in reader:
row = cleanup(row)
print row
Output:
['Phoenix', 'Tucson', 'Flagstaff', 'Salt Lake City', 'Park City', 'Denver', 'Estes Park', 'Colorado Springs', 'Pueblo', 'Albuquerque']
['Miami', 'Jacksonville', 'Macon', 'Charlotte', 'Charleston']
['Pittsburgh', 'Philadelphia', 'Atlantic City', 'Newark', 'Baltimore', 'D.C.', 'Richmond', 'Charleston', 'Dover']
import re
s = "If you have vacation or wedding plans for Miami, Jacksonville, Macon, Charlotte, or Charleston, expect a couple systems"
p = re.compile(r"If you have vacation or wedding plans (in|for) ((\w+, )+)or (\w+)")
m = p.match(s)
print m.group(2) # output: Miami, Jacksonville, Macon, Charlotte,
cities = m.group(2).split(", ") # cities = ['Miami', 'Jacksonville', 'Macon', 'Charlotte', '']
cities[-1] = m.group(4) # add the city after or
print cities # cities = ['Miami', 'Jacksonville', 'Macon', 'Charlotte', 'Charleston']
the city can be matched by pattern (\w+, ) and or (\w+)
and split cities by pattern ,
btw, as the pattern is used to many data, it is preferred to work with the compiled object
PS: the word comes after plan can be for or in, according to examples you provide
How about this
>>> text = 'If you have vacation or wedding plans for Phoenix, Tucson, Flagstaff, Salt Lake City, Park City, Denver, Estes Park, Colorado Springs, Pueblo, or Albuquerque, the week will'
>>> match = re.search(r'^If you have vacation or wedding plans (in?|for?) ([\w+ ,]+)',text).groups()[1].split(", ")
Output
>>> match
['Phoenix', 'Tucson', 'Flagstaff', 'Salt Lake City', 'Park City', 'Denver', 'Estes Park', 'Colorado Springs', 'Pueblo', 'or Albuquerque', 'the week will']

Categories