I'm studying Python steadily at freeCodeCamp. In the previous article (https://qiita.com/makky0620/items/0f5dbcdd77b5b10cce96), I challenged ** Python for Everybody ** and ** Arithmetic Formatter **. This time I will challenge ** Time Calculator **.
The final thing I want is the ʻadd_time` method, and the behavior is as follows
add_time("3:00 PM", "3:10")
# Returns: 6:10 PM
add_time("11:30 AM", "2:32", "Monday")
# Returns: 2:02 PM, Monday
add_time("11:43 AM", "00:20")
# Returns: 12:03 PM
add_time("10:10 PM", "3:30")
# Returns: 1:40 AM (next day)
add_time("11:43 PM", "24:20", "tueSday")
# Returns: 12:03 AM, Thursday (2 days later)
add_time("6:30 PM", "205:12")
# Returns: 7:42 AM (9 days later)
datetime
and add the second argument with:
divided into hours and minutes.uppercase + lowercase
in the preprocessing (because there was tueSday etc.).As a method to convert date and time and character string to each other
strptime ()
: String-> Convert to date and timestrftime ()
: Date and time-> Convert to stringthere is. strftime ()
can output the day of the week by using a formatting code such as % A
or% a
. There is also a formatting code of % p
for 12-hour tables like AM / PM.
import datetime
dt = datetime.datetime(2020, 7, 13)
print(dt.strftime('%A, %a'))
# Monday, Mon
However, strptime ()
could not receive the day of the week with% a
etc. (Because you don't know the day of the week unless the date is decided ...)
import datetime
dt_str = "7:49 Wednesday"
format = "%H:%M %A"
dt = datetime.strptime(dt_str, format)
print(dt.strftime("%H:%M %A"))
# 07:49 Monday
So, I made a list of days of the week and implemented it.
weeks = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
def get_week_by_diff(week, diff):
index = weeks.index(week)
target_index (index + diff) % len(weeks)
return weeks[target_index]
I felt it was easier than the previous problem.
The next issue is * Budget App *.
Recommended Posts