我将如何处理这个过程?假设有人输入“3:5”,我应该能够得到输出“3:05 AM”。或者,如果有人输入“00:00”,我应该得到“12:00 AM”。如果时间格式只是输入为“hhmm”,我会意识到过多的方法,但输入的范围可以是“h:m”,“hh:m”,“hh:m”和“hh:毫米”。所以这是非常情境化的。
def timeConvert():
miliTime = int(input("Enter a time in hh:mm (military) format: "))
miliTime.split(":")
if len(miliTime) == 3:
hours = miliTime[0]
minutes = miliTime[2]
if hours < 0:
print("Hours can't be less than 0.")
elif len(miliTime) == 4:
if miliTime[0:2] >= 10:
hours = militime[0:2]
minutes = militime[3]
if minutes < 0:
print("Minutes can't be less than 0.")
if minutes < 10:
minutes = 0 + minutes
else:
hours = miliTime[0]
minutes = militime[2:]
if minutes >= 60:
print("Too big of a number for minutes.")
else:
hours = miliTime[0:2]
minutes = miliTime[3:]
setting = AM
if hours > 12:
setting = PM
hours -= 12
print(hours + ":" + minutes + setting)
timeConvert()
答案 0 :(得分:6)
使用datetime模块的strptime()
将字符串作为日期时间对象读取,然后使用strftime()
将其转换回字符串,例如 -
>>> datetime.datetime.strptime('3:5','%H:%M').strftime('%I:%M %p')
'03:05 AM'
>>> datetime.datetime.strptime('18:30','%H:%M').strftime('%I:%M %p')
'06:30 PM'
>>> datetime.datetime.strptime('00:00','%H:%M').strftime('%I:%M %p')
'12:00 AM'
解释的格式 -
%H - 小时(24小时fomrat)
%M - 分钟
%I - 小时(12小时格式)
%p - AM或PM
功能看起来像 -
def timeConvert():
import datetime
ds = input("Enter a time in hh:mm (military) format: ")
newds = datetime.datetime.strptime(ds, ,'%H:%M').strftime('%I:%M %p')
print(newds)
答案 1 :(得分:1)
将输入分割为:
,并在最后使用格式化输出:
def timeConvert():
miliTime = input("Enter a time in hh:mm (military) format: ")
hours, minutes = miliTime.split(":")
hours, minutes = int(hours), int(minutes)
setting = "AM"
if hours > 12:
setting = "PM"
hours -= 12
print(("%02d:%02d" + setting) % (hours, minutes))
答案 2 :(得分:0)
您可以简单地将2列合并为一个字符串函数。我假设您正在使用24小时制或军事时间(精确到100分钟)
import pandas as pd
df = pd.read_clipboard()
for i in df.columns:
df[i] = df[i].apply(str)
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'].apply(lambda x: x.zfill(4)))
df
Out[11]:
ccy date time open high low close datetime
0 EURUSD 20190211 100 1.1318 1.1319 1.1317 1.1319 2019-02-11 01:00:00
1 EURUSD 20190211 200 1.132 1.1322 1.1319 1.1319 2019-02-11 02:00:00
2 EURUSD 20190211 300 1.1318 1.1319 1.1318 1.1319 2019-02-11 03:00:00
3 EURUSD 20190211 400 1.1319 1.1319 1.1318 1.1318 2019-02-11 04:00:00
4 EURUSD 20190211 500 1.1318 1.1318 1.1318 1.1318 2019-02-11 05:00:00
答案 3 :(得分:0)
military_time = input("Enter a military time (0000 to 2359): ")
hours = int(military_time[0:2])
minutes = int(military_time[2:4])
if hours >= 12:
meridian = "pm"
hours %= 12
else:
meridian = "am"
if hours == 0:
hours = 12
print("The regular time is {0}:{1} {2}.".format(hours, minutes, meridian))