Python program to convert a 24 hour format to 12 hour formatDate Format providerPUT (Parallel Universe Time) generatorConverting seconds to hours, minutes and secondsCalculate attendance compliance based on attendance recordImplementing a week schedule class in C#Output a flight schedule, formatted in military timePython - Faster random business date generationPretty print uptime given seconds and omit unnecessary stringsCode Vita: Form the maximum possible time in the HH:MM:SS format using any six of nine given single digitsPython program to calculate the sun angle
Word for a small burst of laughter that can't be held back
California: "For quality assurance, this phone call is being recorded"
Is the decompression of compressed and encrypted data without decryption also theoretically impossible?
What is the history of the check mark / tick mark?
What does War Machine's "Canopy! Canopy!" line mean in "Avengers: Endgame"?
Traffic law UK, pedestrians
Credit card offering 0.5 miles for every cent rounded up. Too good to be true?
What happens to foam insulation board after you pour concrete slab?
Does the growth of home value benefit from compound interest?
Is there any word or phrase for negative bearing?
What's the correct term for a waitress in the Middle Ages?
How to decline physical affection from a child whose parents are pressuring them?
Riley's, assemble!
What are the words for people who cause trouble believing they know better?
Comma Code - Ch. 4 Automate the Boring Stuff
Do manufacturers try make their components as close to ideal ones as possible?
Accidentally renamed tar.gz file to a non tar.gz file, will my file be messed up
Past participle agreement with the subject in the case of pronominal verbs
Personalization conditions switching doesn`t work in Experience Editor (9.1.0, Initial Release)
Diet Coke or water?
3 as a Sum of 3 Pan Digital Expressions
Poisson distribution: why does time between events follow an exponential distribution?
Short story written from alien perspective with this line: "It's too bright to look at, so they don't"
Do I include animal companions when calculating difficulty of an encounter?
Python program to convert a 24 hour format to 12 hour format
Date Format providerPUT (Parallel Universe Time) generatorConverting seconds to hours, minutes and secondsCalculate attendance compliance based on attendance recordImplementing a week schedule class in C#Output a flight schedule, formatted in military timePython - Faster random business date generationPretty print uptime given seconds and omit unnecessary stringsCode Vita: Form the maximum possible time in the HH:MM:SS format using any six of nine given single digitsPython program to calculate the sun angle
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:
- The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
- When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'
For example:
12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.
The code:
import datetime
def time_converter(time):
midday_dt = datetime.datetime.strptime('12:00','%H:%M')
time_dt = datetime.datetime.strptime(time, '%H:%M')
if time_dt >= midday_dt:
if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes'
time += ' p.m.'
else:
if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
time = time[1:]
if is_midnight(time_dt):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes:02d'
time += ' a.m.'
return time
def clamp_to_twelve(time_dt, midday_dt):
clamp_dt = time_dt - midday_dt
minutes, seconds = divmod(clamp_dt.seconds, 60)
hours, minutes = divmod(minutes, 60)
return [hours, minutes]
def is_midnight(time_dt):
return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
time_dt <= datetime.datetime.strptime('00:59','%H:%M'))
if __name__ == '__main__':
assert time_converter('12:30') == '12:30 p.m.'
assert time_converter('09:00') == '9:00 a.m.'
assert time_converter('23:15') == '11:15 p.m.'
python beginner datetime formatting
$endgroup$
add a comment |
$begingroup$
Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:
- The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
- When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'
For example:
12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.
The code:
import datetime
def time_converter(time):
midday_dt = datetime.datetime.strptime('12:00','%H:%M')
time_dt = datetime.datetime.strptime(time, '%H:%M')
if time_dt >= midday_dt:
if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes'
time += ' p.m.'
else:
if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
time = time[1:]
if is_midnight(time_dt):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes:02d'
time += ' a.m.'
return time
def clamp_to_twelve(time_dt, midday_dt):
clamp_dt = time_dt - midday_dt
minutes, seconds = divmod(clamp_dt.seconds, 60)
hours, minutes = divmod(minutes, 60)
return [hours, minutes]
def is_midnight(time_dt):
return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
time_dt <= datetime.datetime.strptime('00:59','%H:%M'))
if __name__ == '__main__':
assert time_converter('12:30') == '12:30 p.m.'
assert time_converter('09:00') == '9:00 a.m.'
assert time_converter('23:15') == '11:15 p.m.'
python beginner datetime formatting
$endgroup$
add a comment |
$begingroup$
Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:
- The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
- When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'
For example:
12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.
The code:
import datetime
def time_converter(time):
midday_dt = datetime.datetime.strptime('12:00','%H:%M')
time_dt = datetime.datetime.strptime(time, '%H:%M')
if time_dt >= midday_dt:
if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes'
time += ' p.m.'
else:
if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
time = time[1:]
if is_midnight(time_dt):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes:02d'
time += ' a.m.'
return time
def clamp_to_twelve(time_dt, midday_dt):
clamp_dt = time_dt - midday_dt
minutes, seconds = divmod(clamp_dt.seconds, 60)
hours, minutes = divmod(minutes, 60)
return [hours, minutes]
def is_midnight(time_dt):
return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
time_dt <= datetime.datetime.strptime('00:59','%H:%M'))
if __name__ == '__main__':
assert time_converter('12:30') == '12:30 p.m.'
assert time_converter('09:00') == '9:00 a.m.'
assert time_converter('23:15') == '11:15 p.m.'
python beginner datetime formatting
$endgroup$
Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:
- The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
- When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'
For example:
12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.
The code:
import datetime
def time_converter(time):
midday_dt = datetime.datetime.strptime('12:00','%H:%M')
time_dt = datetime.datetime.strptime(time, '%H:%M')
if time_dt >= midday_dt:
if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes'
time += ' p.m.'
else:
if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
time = time[1:]
if is_midnight(time_dt):
hours, minutes = clamp_to_twelve(time_dt, midday_dt)
time = f'hours:minutes:02d'
time += ' a.m.'
return time
def clamp_to_twelve(time_dt, midday_dt):
clamp_dt = time_dt - midday_dt
minutes, seconds = divmod(clamp_dt.seconds, 60)
hours, minutes = divmod(minutes, 60)
return [hours, minutes]
def is_midnight(time_dt):
return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
time_dt <= datetime.datetime.strptime('00:59','%H:%M'))
if __name__ == '__main__':
assert time_converter('12:30') == '12:30 p.m.'
assert time_converter('09:00') == '9:00 a.m.'
assert time_converter('23:15') == '11:15 p.m.'
python beginner datetime formatting
python beginner datetime formatting
edited May 26 at 12:55
200_success
133k20160429
133k20160429
asked May 26 at 8:12
enoyenoy
37217
37217
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$begingroup$
You don't need such a long program for such a short task. You can make it considerably shorter,
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.
>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.
The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).
replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)
You can use strftime for your requirements and you can take a look at this too.
NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).
Hope this helps!
$endgroup$
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221042%2fpython-program-to-convert-a-24-hour-format-to-12-hour-format%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
You don't need such a long program for such a short task. You can make it considerably shorter,
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.
>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.
The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).
replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)
You can use strftime for your requirements and you can take a look at this too.
NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).
Hope this helps!
$endgroup$
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
add a comment |
$begingroup$
You don't need such a long program for such a short task. You can make it considerably shorter,
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.
>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.
The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).
replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)
You can use strftime for your requirements and you can take a look at this too.
NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).
Hope this helps!
$endgroup$
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
add a comment |
$begingroup$
You don't need such a long program for such a short task. You can make it considerably shorter,
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.
>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.
The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).
replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)
You can use strftime for your requirements and you can take a look at this too.
NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).
Hope this helps!
$endgroup$
You don't need such a long program for such a short task. You can make it considerably shorter,
>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.
>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.
The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).
replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.
Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)
You can use strftime for your requirements and you can take a look at this too.
NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).
Hope this helps!
edited May 28 at 18:47
answered May 26 at 12:23
JustinJustin
1,100226
1,100226
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
add a comment |
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
$begingroup$
@enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :)
$endgroup$
– Justin
May 27 at 11:04
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f221042%2fpython-program-to-convert-a-24-hour-format-to-12-hour-format%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown