当前位置: 代码迷 >> 综合 >> HOME: Date and Time Converter
  详细解决方案

HOME: Date and Time Converter

热度:40   发布时间:2024-02-05 06:47:25.0

题目

Computer date and time format consists only of numbers, for example: 21.05.2018 16:30
Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes
Your task is simple - convert the input date and time from computer format into a “human” format.
在这里插入图片描述
Input: Date and time as a string

Output: The same date and time, but in a more readable format

Example:

date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes"
date_time("19.09.2999 01:59") == "19 September 2999 year 1 hour 59 minutes"
date_time("21.10.1999 18:01") == "21 October 1999 year 18 hours 1 minute"
# NB: words "hour" and "minute" are used only when time is 01:mm (1 hour) or hh:01 (1 minute).
# In other cases it should be used "hours" and "minutes".

How it is used: To improve the understanding between computers and humans.

Precondition:
0 < date <= 31
0 < month <= 12
0 < year <= 3000
0 < hours < 24
0 < minutes < 60

注意: 如果小时或者分钟是1,hour和minute是单数形式

难度: Elementary+

思路及代码

思路

  1. 将给的时间里的年月日和时分提取出来(整数格式)
  2. 写出数字月份和单词月份的对应的字典
  3. 判断小时或分钟是否等于1,如果是1就将“hours”和“minutes”的复数去掉换为单数形式(4种情况,都是1,有1个是1,都不是1)
  4. 返回格式化字符串

代码

def date_time(time: str) -> str:#replace this for solutionday, month, year, hour, minute = map(int, (time[:2], time[3:5], time[6:11], time[-5:-3], time[-2:]))month_dict = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'}if hour == 1 and minute ==1:tlp = '{} {} {} year {} hour {} minute'elif minute == 1:tlp = '{} {} {} year {} hours {} minute'elif hour == 1:tlp = '{} {} {} year {} hour {} minutes'else:tlp = '{} {} {} year {} hours {} minutes'result = tlp.format(day, month_dict[month], year, hour, minute)return resultif __name__ == '__main__':print("Example:")print(date_time('01.01.2000 00:00'))#These "asserts" using only for self-checking and not necessary for auto-testingassert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"print("Coding complete? Click 'Check' to earn cool rewards!")

优秀代码

No.1

from datetime import datetimedef date_time(time):dt = datetime.strptime(time, '%d.%m.%Y %H:%M')hour = 'hour' if dt.hour == 1 else 'hours'    minute = 'minute' if dt.minute == 1 else 'minutes'return dt.strftime(f'%#d %B %Y year %#H {hour} %#M {minute}')    

先用 datetime.strptime() 函数将 time 解析为日月年、时分的格式,然后定义hour和minute的单位,最后用 date.strptime() 函数将时间格式化输出。最后格式化时间的部分可以用 %# 将数字格式化,如:小时是 00 ,就会格式化为 0
感觉自己日期函数这边学的不太好,对现有的一些函数不了解。。。

No.2

from datetime import datetimedef date_time(time):t = datetime.strptime(time, '%d.%m.%Y %H:%M')y, m, d, h, mi =  t.year, datetime.strftime(t, '%B'), t.day, t.hour, t.minutesuffix = lambda n:'s' if n != 1 else ''return f'{d} {m} {y} year {h} hour{suffix(h)} {mi} minute{suffix(mi)}'

这里用 lambda 函数来判断hour和minute后面用不用加“s”。

No.3

from datetime import datetimedef checkio(dt):dt = datetime.strptime(dt, '%d.%m.%Y %H:%M')p = lambda attr: attr + 's' * (getattr(dt, attr) != 1)return dt.strftime(f'%-d %B %Y year %-H {p("hour")} %-M {p("minute")}')

getattr() 函数获得属性值来判断hour和minute后面用不用加“s”。

知识点

1. date.strptime() 函数

根据指定的格式(format)把一个时间字符串(str)解析为时间元组。
语法:datetime.strptime(str[, format])
参数:str:时间字符串;format:格式化字符串(解析的格式)
返回值: struct_time对象。
python中时间日期格式化符号:
在这里插入图片描述

2. datetime.strftime() 函数

可以看成上一个的逆函数,是将一个时间元组进行格式化:接收时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定。
语法:datetime.strftime(format[, t])
参数:format:格式字符串;t:时间元组。

3. getattr() 函数

用于返回一个对象属性值。
语法:getattr(object, name[, default])
参数:object:对象;name:字符串,对象属性;default:默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
返回值: 返回对象属性值。
eg:

class A(object):bar = 1
a = A()
getattr(a, 'bar')  # 获取属性 bar 值;结果是1
  相关解决方案