Related
def main():
# Initialize dictionaries
rooms = { 'CS101':3004, 'CS102':4501, 'CS103':6755,
'NT110':1244, 'CM241':1411}
instructors = {'CS101':'Haynes', 'CS102':'Alvarado',
'CS103':'Rich', 'NT110':'Burke',
'CM241':'Lee'}
times = {'CS101':'8:00 am', 'CS102':'9:00 am',
'CS103':'10:00 am', 'NT110':'11:00 am',
'CM241':'12:00 pm'}
course = input('Enter a course number:' )
if course not in rooms:
print(course, 'is an invalid course number.')
else:
print('The details for course', course, 'are:')
print('Room:', rooms)
print('Instructor:', instructors[course])
print('Time:', times)
# Call the main function.
main()
Once I write the corresponding course number I should get the corresponding answer, instead I get everything.
You have three dictionaries (you should really only have one due to the repetition of the course code). However, based on what you currently have you need ensure that the course code exists in all three dictionaries.
def main():
# Initialize dictionaries
rooms = { 'CS101':3004, 'CS102':4501, 'CS103':6755,
'NT110':1244, 'CM241':1411}
instructors = {'CS101':'Haynes', 'CS102':'Alvarado',
'CS103':'Rich', 'NT110':'Burke',
'CM241':'Lee'}
times = {'CS101':'8:00 am', 'CS102':'9:00 am',
'CS103':'10:00 am', 'NT110':'11:00 am',
'CM241':'12:00 pm'}
course = input('Enter a course number: ' )
if course in rooms and course in times and course in instructors:
print('The details for course', course, 'are:')
print('Room:', rooms[course])
print('Instructor:', instructors[course])
print('Time:', times[course])
else:
print('Invalid course')
# Call the main function.
main()
A better construct could be:
def main():
courses = {'CS101': {'room': 3004, 'instructor': 'Haynes', 'time': '8:00 am'},
'CS102': {'room': 4501, 'instructor': 'Alvarado', 'time': '9:00 am'},
'CS103': {'room': 6755, 'instructor': 'Rich', 'time': '10:00 am'},
'NT110': {'room': 1244, 'instructor': 'Burke', 'time': '11:00 am'},
'CM241': {'room': 1411, 'instructor': 'Lee', 'time': '12:00 am'}}
course = input('Enter a course number: ')
if cd := courses.get(course):
print('The details for course', course, 'are:')
print('Room: {}\nInstructor: {}\nTime: {}'.format(*cd.values()))
else:
print('Invalid course')
# Call the main function.
main()
What stopping you replicate logic of intsructor as you done correctly. do same for rest.
def main():
# Initialize dictionaries
rooms = { 'CS101':3004, 'CS102':4501, 'CS103':6755,
'NT110':1244, 'CM241':1411}
instructors = {'CS101':'Haynes', 'CS102':'Alvarado',
'CS103':'Rich', 'NT110':'Burke',
'CM241':'Lee'}
times = {'CS101':'8:00 am', 'CS102':'9:00 am',
'CS103':'10:00 am', 'NT110':'11:00 am',
'CM241':'12:00 pm'}
course = input('Enter a course number:' )
if course not in rooms:
print(course, 'is an invalid course number.')
else:
print('The details for course', course, 'are:')
print('Room:', rooms[course])
print('Instructor:', instructors[course])
print('Time:', times[course])
# Call the main function.
main()
Sample outputs #
Enter a course number:CS101
The details for course CS101 are:
Room: 3004
Instructor: Haynes
Time: 8:00 am
The problem is that when you are trying to print out the dictionary, you are not accessing the value and instead trying to print out the whole dictionary in some cases.
Here's how you can fix this:
def main():
# Initialize dictionaries
rooms = {'CS101': 3004, 'CS102': 4501, 'CS103': 6755, 'NT110': 1244, 'CM241': 1411}
instructors = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'}
times = {'CS101': '8:00 am', 'CS102': '9:00 am', 'CS103': '10:00 am', 'NT110': '11:00 am', 'CM241': '12:00 pm'}
course = input('Enter a course number:')
if course not in rooms:
print(course, 'is an invalid course number.')
else if course not in instructors:
print(course, 'is an invalid course number.')
else if course not in times:
print(course, 'is an invalid course number.')
else:
print('The details for course', course, 'are:')
print('Room:', rooms[course])
print('Instructor:', instructors[course])
print('Time:', times[course])
main()
Hope this helps!
I have started leaning python programming.I am making the project given to me. when ever i give input it says invalid option. i am not able to solve the problem .i don't know were i am going wrong. i have tried every thing that i know. please help !
my output
python bikeshare.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
Invalid choice...
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
thank you for the help
import time
import pandas as pd
import numpy as np
CHICAGO = 'Chicago'
NYC = 'New York City'
WASHINGTON = 'Washington'
CITY_DATA = { CHICAGO: 'chicago.csv',
NYC: 'new_york_city.csv',
WASHINGTON: 'washington.csv' }
DAYS_OF_WEEK = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday']
MONTHS_OF_YEAR = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
HOURS = [
'12 AM'
'1 AM',
'2 AM',
'3 AM',
'4 AM',
'5 AM',
'6 AM',
'7 AM',
'8 AM',
'9 AM',
'10 AM',
'11 AM',
'12 PM',
'1 PM',
'2 PM',
'3 PM',
'4 PM',
'5 PM',
'6 PM',
'7 PM',
'8 PM',
'9 PM',
'10 PM',
'11 PM'
]
MINUTE_SEC = 60
HOUR_SEC = 60 * MINUTE_SEC
DAY_SEC = 24 * HOUR_SEC
WEEK_SEC = 7 * DAY_SEC
# print(CITY_DATA)
START_TIME = 'Start Time'
END_TIME = 'End Time'
BIRTH_YEAR = 'Birth Year'
START_STATION = 'Start Station'
END_STATION = 'End Station'
TRIP_DURATION = 'Trip Duration'
GENDER = 'Gender'
# Added columns
START_MONTH = 'Start Month'
START_DAY_OF_WEEK = 'Start Day of Week'
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(int) month - name of the month to filter by, or "all" to apply no month filter
(int) day - name of the day of week to filter by, or "all" to apply no day filter
"""
invalid_choice = "Invalid choice..."
ALL = 'all'
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
while True:
print("Please enter the number of which city you would like to explore: ")
print("1 Chicago, 2 New York City, 3 Washington")
location = input(">")
if location == '1':
city = CHICAGO
print("You chose Chicago")
break
elif location == '2':
city = NYC
print("You chose New York City")
break
elif location == '3':
city = WASHINGTON
print("You chose Washington")
break
else:
print(invalid_choice)
while True:
get_city = input('\nHello! Let\'s explore some US bikeshare data!\n'
'Would you like to see data for Chicago, New York, or Washington?\n')
if get_city.lower() in ('chicago', 'new york', 'washington'):
if get_city.lower() == 'chicago':
city_filename = chicago
elif get_city.lower() == 'new york':
city_filename = new_york_city
elif get_city.lower() == 'washington':
city_filename = washington
break
print('Enter a valid city name provided in the options')
while True:
print("Please enter the number of the (start) month you would like to explore or \"{}\": ".format(ALL))
print("1 January ... 6 June")
m = input(">")
if m == ALL:
month = None
break
try:
month = int(m)
except ValueError:
print(invalid_choice)
continue
else:
if month >= 1 and month<=6:
print("You chose " + MONTHS_OF_YEAR[month-1])
break
elif month <= 12:
print("Only January to June are in this dataset")
print(invalid_choice)
continue
else:
print(invalid_choice)
continue
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
print("Please enter the number of the (start) day of the week that you would like to explore or \"{}\": ".format(ALL))
print("1 Monday ... 7 Sunday")
d = input("> ")
if d == ALL:
day = None
break
try:
day = int(d)
except ValueError:
print(invalid_choice)
continue
else:
if day >= 1 and day<=7:
day -= 1
print("You chose " + DAYS_OF_WEEK[day])
break
else:
print(invalid_choice)
continue
print_divider()
return city, month, day
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, month is None, day is None)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
trip_length_time_of_day_correlation(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
print("Bye!")
break
if __name__ == "__main__":
main()
The code worked with me... How are you running it?
Your comparison is looking for the number as a string. If you use the standard input (eg, running in a terminal), then it will read it in as a string. But, if you pass in an integer somehow, then it won't match.
neil~$ python stack.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
You chose Chicago
Hello! Let's explore some US bikeshare data!
Would you like to see data for Chicago, New York, or Washington?
I have bellow text( get repsond from Zebra):
30.0 DARKNESS
4 IPS PRINT SPEED
+000 TEAR OFF
TEAR OFF PRINT MODE
GAP/NOTCH MEDIA TYPE
WEB SENSOR TYPE
MANUAL SENSOR SELECT
THERMAL-TRANS. PRINT METHOD
480 PRINT WIDTH
0387 LABEL LENGTH
39.0IN 975MM MAXIMUM LENGTH
CONNECTED USB COMM.
BIDIRECTIONAL PARALLEL COMM.
9600 BAUD
8 BITS DATA BITS
NONE PARITY
DTR & XON/XOFF HOST HANDSHAKE
NONE PROTOCOL
AUTO SER COMM. MODE
<~> 7EH CONTROL CHAR
<^> 5EH COMMAND CHAR
<,> 2CH DELIM. CHAR
ZPL II ZPL MODE
NO MOTION MEDIA POWER UP
FEED
I want to get values for each settings via python.
Expect to get something like a dict {'DARKNESS':30,'PRINT SPEED':'4 IPS' ....}
Normally, expect code is
for line in lines:
x=line.split(' ')
the_value=x[0]
the_setting=x[1]
but it's without fixed blankspace.
I don't have good idea to split it.
Using split() function isn't a good choose here.
The value also have blankspace as well.
I was stuck here.
Any idea?
Using my suggestion in combination with yours, I got this to work (I made a txt file with your examples in it):
import re
file = open('untitled.txt','r')
my_dict = {}
for line in file:
x,y = re.split(r'\s{4,}',line.strip())
my_dict[y] = x
This is the output of the dictionary I made with this code:
{'DARKNESS': '30.0', 'PRINT SPEED': '4 IPS', 'TEAR OFF': '+000', 'PRINT MODE': 'TEAR OFF', 'MEDIA TYPE': 'GAP/NOTCH', 'SENSOR TYPE': 'WEB', 'SENSOR SELECT': 'MANUAL', 'PRINT METHOD': 'THERMAL-TRANS.', 'PRINT WIDTH': '480', 'LABEL LENGTH': '0387', 'MAXIMUM LENGTH': '39.0IN 975MM', 'USB COMM.': 'CONNECTED', 'PARALLEL COMM.': 'BIDIRECTIONAL', 'BAUD': '9600', 'DATA BITS': '8 BITS', 'PARITY': 'NONE', 'HOST HANDSHAKE': 'DTR & XON/XOFF', 'PROTOCOL': 'NONE', 'SER COMM. MODE': 'AUTO', 'CONTROL CHAR': '<~> 7EH', 'COMMAND CHAR': '<^> 5EH', 'DELIM. CHAR': '<,> 2CH', 'ZPL MODE': 'ZPL II', 'MEDIA POWER UP': 'NO MOTION'}
well, you can do the following
file=open('yourfile','r').read().split('\n')
lines=[line.split(' ') for line in file]
items=[[i.replace(' ','') for i in item if i!=''] for item in lines]
output_dict={i[0]:i[1] for i in items if i}
I used 3 main features of python here the one line loop
loop=[dosomething(item) for item in array if item=='somevalue'] #if statement is not necessary
,the replace() function
print 'Hello You'.replace('You','world') # outputs hello world
and the split() function
print 'hello,world'.split(',') # outputs ['hello',world]
you can find more documentation here: python string methods
Thanks #TheDetective , you answer is useful.
Now better.
(comments have string limit,so I have to post in answer)
>>> for line in lines:
... re.split(r'\s{4,}',line.rstrip().lstrip())
...
['\x02 30.0', 'DARKNESS']
['4 IPS', 'PRINT SPEED']
['+000', 'TEAR OFF']
['TEAR OFF', 'PRINT MODE']
['GAP/NOTCH', 'MEDIA TYPE']
['WEB', 'SENSOR TYPE']
['MANUAL', 'SENSOR SELECT']
['THERMAL-TRANS.', 'PRINT METHOD']
['480', 'PRINT WIDTH']
['0387', 'LABEL LENGTH']
['39.0IN 975MM', 'MAXIMUM LENGTH']
['CONNECTED', 'USB COMM.']
['BIDIRECTIONAL', 'PARALLEL COMM.']
['9600', 'BAUD']
['8 BITS', 'DATA BITS']
['NONE', 'PARITY']
['DTR & XON/XOFF', 'HOST HANDSHAKE']
['NONE', 'PROTOCOL']
['AUTO', 'SER COMM. MODE']
['<~> 7EH', 'CONTROL CHAR']
['<^> 5EH', 'COMMAND CHAR']
['<,> 2CH', 'DELIM. CHAR']
['ZPL II', 'ZPL MODE']
['NO MOTION', 'MEDIA POWER UP']
['FEED']
>>>
Since I've already done it, you might as well have my answer too.
The two items of information occupy fixed places on each line. Therefore, string slicing can be used to pick them from lines. I omit the last line because there is no information about its field name.
>>> result = {}
>>> with open('temp.txt') as temp:
... for line in temp.readlines():
... if line.startswith('FEED'):
... break
... result[line[20:].strip()] = line[:20].strip()
...
>>> result
{'DARKNESS': '30.0', 'PARITY': 'NONE', 'PRINT WIDTH': '480', 'DATA BITS': '8 BITS', 'PROTOCOL': 'NONE', 'COMMAND CHAR': '<^> 5EH', 'USB COMM.': 'CONNECTED', 'BAUD': '9600', 'PRINT MODE': 'TEAR OFF', 'MEDIA POWER UP': 'NO MOTION', 'DELIM. CHAR': '<,> 2CH', 'MAXIMUM LENGTH': '39.0IN 975MM', 'SENSOR SELECT': 'MANUAL', 'SENSOR TYPE': 'WEB', 'LABEL LENGTH': '0387', 'PARALLEL COMM.': 'BIDIRECTIONAL', 'CONTROL CHAR': '<~> 7EH', 'TEAR OFF': '+000', 'PRINT SPEED': '4 IPS', 'PRINT METHOD': 'THERMAL-TRANS.', 'HOST HANDSHAKE': 'DTR & XON/XOFF', 'ZPL MODE': 'ZPL II', 'MEDIA TYPE': 'GAP/NOTCH', 'SER COMM. MODE': 'AUTO'}
Use the python split function
https://www.tutorialspoint.com/python/string_split.htm
You can iterate over the lines using split('\n')
and then you can use regex to split the rest.
In your accepted answer it only splits when the whitespace between the key and value is 4 or bigger. This can give buggs when it is smaller. My solution normally fixes this.
dict = {}
for line in input.split('\n'):
# Split the line in the correct parts
myArray = re.findall('(^.{20})(.*)', line.lstrip().rstrip())
# Check that you have found both key and value
if len(myArray) > 0:
myTupple = myArray[0]
dict[myTupple[1].rstrip()] = myTupple[0].rstrip()
Im trying to learn html scraping for a project, I'm using python and lxml. I've been successful so far in getting the data I needed but now I have another problem. The site that I'm scraping from (op.gg) when you scroll down it adds new tables with more information. When I run my script (below) it only gets the first 50 entries and nothing more. My question is how can I get at least the first 200 names on the page or if it is even possible.
from lxml import html
import requests
page = requests.get('https://na.op.gg/ranking/ladder/')
tree = html.fromstring(page.content)
names = tree.xpath('//td[#class="SummonerName Cell"]/a/text()')
print (names)
Borrow the idea from Pedro, https://na.op.gg/ranking/ajax2/ladders/start=number will give you 50 records start from number, for example:
https://na.op.gg/ranking/ajax2/ladders/start=0 get (1-50),
https://na.op.gg/ranking/ajax2/ladders/start=50 get (51-100),
https://na.op.gg/ranking/ajax2/ladders/start=100 get (101-150),
https://na.op.gg/ranking/ajax2/ladders/start=150 get (151-200),
etc....
After that you could change your scrap code, as the page is different as your original one, suppose you want get first 200 names, here is the amended code:
from lxml import html
import requests
start_url = 'https://na.op.gg/ranking/ajax2/ladders/start='
names_200 = list()
for i in [0,50,100,150]:
dest_url = start_url + str(i)
page = requests.get(dest_url)
tree = html.fromstring(page.content)
names_50 = tree.xpath('//a[not(#target) and not(#onclick)]/text()')
names_200.extend(names_50)
print names_200
print len(names_200)
Output:
[u'am\xc3\xa9liorer', 'pireaNn', 'C9 Ray', 'P1 Pirean', 'Pobelter', 'mulgokizary', 'consensual clown', 'Jue VioIe Grace', 'Deep Learning', 'Keegun', 'Free Papa Chau', 'C9 Gun', 'Dhokla', 'Arrowlol', 'FOX Brandini', 'Jurassiq', 'Win or Learn', 'Acoldblazeolive', u'R\xc3\xa9venge', u'M\xc3\xa9ru', 'Imaqtpie', 'Rohammers', 'blaberfish2', 'qldurtms', u'd\xc3\xa0wolfsclaw', 'TheOddOrange', 'PandaTv 656826', 'stuntopolis', 'Butler Delta', 'P1 Shady', 'Entranced', u'Linsan\xc3\xadty', 'Ablazeolive', 'BukZacH', 'Anivia Kid', 'Contractz', 'Eitori', 'MistyStumpey', 'Prodedgy', 'Splitting', u'S\xc4\x99b B\xc4\x99rnal', 'N For New York', 'Naeun', '5tunt', 'C9 Winter', 'Doubtfull', 'MikeYeung', 'Rikara', u'RAH\xc3\x9cLK', ' Sudzzi', 'joong ki song', 'xWeixin VinLeous', 'rhubarbs', u'Ch\xc3\xa0se', 'XueGao', 'Erry', 'C9 EonYoung', 'Yeonbee', 'M ckg', u'Ari\xc3\xa1na Lovato', 'OmarGod', 'Wiggily', 'lmpactful', 'Str1fe', 'LL Stylish', '2017', 'FlREFLY', 'God Fist Monk', 'rWeiXin VinLeous', 'Grigne', 'fantastic ad', 'bobqinX', 'grigne 1v10', 'Sora1', 'Juuichi san ', 'duoking2', 'SandPaperX', 'Xinthus', 'TwichTv CoMMa', 'xFSN Rin', 'UBC CJ', 'PotIuck', 'DarkWingsForSale', 'Get After lt', 'old chicken', u'\xc4\x86ris', 'VK Deemo', 'Pekin Woof', 'YIlIlIlIlI', 'RiceLegend', 'Chimonaa1', 'DJNDREE5', u'CloudNguy\xc3\xa9n', 'Diamond 1 Khazix', 'dawolfsfang', 'clg imaqtpie69', 'Pyrites', 'Lava', 'Rathma', 'PieCakeLord', 'feed l0rd', 'Eygon', 'Autolycus1', 'FateFalls 20xx', 'nIsHIlEzHIlA', 'C9 Sword', 'TET Fear', 'a very bad time', u'Jur\xc3\xa1ssiq', 'Ginormous Noob', 'Saskioo', 'S D 2 NA', 'C9 Smoothie', 'dufTlalgkqtlek', 'Pants are Dragon', u'H\xc3\xb3llywood', 'Serenitty', 'Waggily ', 'never lucky help', u'insan\xc3\xadty', 'Joyul', 'TheeBrandini', 'FoTheWin', 'RyuShoryu', 'avi is me', 'iKingVex', 'PrismaI', 'An Obese Panda', 'TdollasAKATmoney', 'feud999', 'Soligo', 'Steel I', 'SNH48 Ruri', 'BillyBoss1', 'Annie Bot', 'Descraton', 'Cris', 'GrayHoves', 'RegisZZ', 'lron Pyrite', 'Zaion', 'Allorim', 't d', u'Alex \xc3\xafch', 'godrjsdnd', 'DOUBLELIFTSUCKS', 'John Mcrae', u'Lobo Solitari\xc3\xb3', 'MikeYeunglol', 'i xo u', 'NoahMost', 'Vsionz', 'GladeGleamBright', 'Tuesdayy', 'RealDarkness', 'CC Dean', 'na mid xd LFT', 'Piggy Kitten', 'Abou222', 'TG Strompest', 'MooseHater', 'Day after Day', 'bat8man', 'AxAxAxAxA', 'Boyfriend', 'EvanRL', '63FYWJMbam', 'Fiftygbl', u'Br\xc4\xb1an', 'MlST', u'S\xc3\xb8ren Bjerg', 'FOX Akaadian', '5word', 'tchikou', 'Hakuho', 'Noobkiller291', 'woxiangwanAD', 'Doublelift', 'Jlaol', u'z\xc3\xa3ts', 'Cow Goes Mooooo', u'Be Like \xc3\x91e\xc3\xb8\xc3\xb8', 'Liquid Painless', 'Zergy', 'Huge Rooster', 'Shiphtur', 'Nikkone', 'wiggily1', 'Dylaran', u'C\xc3\xa0m', 'byulbit', 'dirtybirdy82', 'FreeXpHere', u'V\xc2\xb5lcan', 'KaNKl', 'LCS Actor 4', 'bie sha wo', 'Mookiez', 'BKSMOOTH', 'FatMiku']
200
BTW, you could expand it based on your requirement.
I am importing a large csv file to ETL into a database, and the date format that was originally set in the csv file looks like 4/22/2016 1:00:00 PM. Each date is part of a larger list that might have non-date type items in it. for example:
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
I would like to reformat every date (if present in the list) with the correct MySQL format of
%m-%d-%Y %I:%M:%S
How would i do this with a list comprehension? my code is not working for obvious reasons but i'm not sure where to go from here. I need to retain the index that the date is found in v.
from datetime import datetime, date, time
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
tstamp = datetime.strptime(_params, "%m/%d/%Y %I:%M:%S %p")
newtstamp = date.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
replace = { _params: newtstamp }
l = [replace.get(x, x) for x in _params]
print l
fixdate(v)
Please check this. Comments inline with code.
from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
#First date in list
tstamp = datetime.strptime(_params[0], "%m/%d/%Y %I:%M:%S %p")
#Add %p after %S if AM or PM is required
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[0] = newtstamp
#Second date in list
tstamp = datetime.strptime(_params[1], "%m/%d/%Y %I:%M:%S %p")
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[1] = newtstamp
print "After changing format..."
print _params
fixdate(v)
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>
Code with list comprehension:
from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
_params = [i if ':' not in str(i) and '/' not in str(i) else datetime.strftime(datetime.strptime(i, "%m/%d/%Y %I:%M:%S %p"), "%m-%d-%Y %I:%M:%S") for i in _params]
print "After changing format..."
print _params
fixdate(v)
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>