Неправильное преобразование времени с нецелой разницей по Гринвичу в Python ⇐ Python

Программы на Python
Anonymous
Неправильное преобразование времени с нецелой разницей по Гринвичу в Python

Сообщение Anonymous »

Вот мой код:

Код: Выделить всё

"""GMT converter"""

from datetime import datetime, timedelta

# Input from user
current_time_str = input("")  # Time now
current_gmt = float(input("")) # GMT current
target_gmt = float(input(""))  # Target GMT

# Replace "A.M." and "P.M." with "AM" and "PM" to match the format of strptime.
current_time_str = current_time_str.replace("A.M.", "AM").replace("P.M.", "PM")

# Convert current time from string format to datetime object.
current_time = datetime.strptime(current_time_str, "%I:%M %p")

# Calculate the GMT difference and use timedelta to shift the time.
gmt_difference = target_gmt - current_gmt
time_difference = timedelta(hours=gmt_difference)

# Increase or decrease the GMT time you want to find.
target_time = current_time + time_difference

# Convert target time back to HH:MM A.M./P.M. format.
output_time_str = target_time.strftime("%I:%M %p")

# Replace "AM" and "PM" with "A.M." and "P.M."
output_time_str = output_time_str.replace("AM", "A.M.").replace("PM", "P.M.")

# Output
print(output_time_str)
Пример 1:
Ввод:
15:00. (Сейчас время)
-1 (текущее время по Гринвичу как действительное число)
1 (целевое время по Гринвичу как действительное число)
Выход:
17:00
Пример 2:
Ввод:
13:00
5.30
7
Ожидаемый результат: 14:30
Вместо этого я получил: 14:42.
Когда я запускаю код, пример 1 верен, а пример 2 неверен.

Подробнее здесь: https://stackoverflow.com/questions/790 ... -in-python

Вернуться в «Python»