如何在下面的代码中对这些datetime对象元素数组进行排序?

2024-10-01 00:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用python制作提醒应用程序,但当我尝试为各种任务安排时间时,我可以进行排序,但我需要更改表单,无法返回到原始表单 在这里的sort函数中,我通过使用strtime方法解析字符串,将12小时格式的tr_arr Numpy数组元素转换为datetime格式,但当我对其进行排序并希望将时间原始格式转换为12小时格式时,它显示出错误。 代码如下:

from datetime import datetime as dtm
import numpy as np


def sort_rem(tr_arr,r_arr):
    a=tr_arr
    print(a)
    
    for i in range(len(tr_arr)):
        tr_arr[i]=dtm.strptime(tr_arr[i],"%I:%M:%S %p")
       
    print(tr_arr)
    
    for i in range(len(tr_arr)):
        for j in range(i+1,len(tr_arr)):
            if tr_arr[i]>tr_arr[j]:
                temp=tr_arr[i]
                tr_arr[i]=tr_arr[j]
                tr_arr[j]=temp
                temp=r_arr[i]
                r_arr[i]=r_arr[j]
                r_arr[j]=temp
    print(tr_arr)
    print(r_arr)

    for i in range(len(tr_arr)):
        for j in range(len(tr_arr)):
            if tr_arr[i]==dtm.strptime(a[j],"%I:%M:%S %p"):
                tr_arr[i]=a[j]
                
    print(tr_arr)
    return tr_arr , r_arr


class Alarm():
    def set_alm():
        aH=input("Enter the hour to remind you at:")
        aM=input("Enter the minute to remind you at:")
        aS=input("Enter the second to remind you at:")
        amp=input("Enter AM/PM:")

        if int(aH)<=12 and int(aM)<=59 and int(aS)<=59 and (amp=='AM' or amp=='PM'):
            if len(aH)==1:
                aH='0'+aH
            else:
                pass
            if len(aM)==1:
                aM='0'+aM
            else:
                pass
            if len(aS)==1:
                aS='0'+aS
            else:
                pass
            t_str=f"{aH}:{aM}:{aS} {amp}"
            return t_str

        else:
            print("Please enter values of hour,minute and seconds and AM/PM in correct range!!")
    
n_task=int(input("Enter the number of tasks for the reminder:"))

rem_arr=np.array([])
trem_arr=np.array([])
for i in range(n_task):
    rem=input("Enter the task you want to do:")
    rem_arr=np.append(rem_arr,rem)
    trem=Alarm.set_alm()
    trem_arr=np.append(trem_arr,trem)


print(trem_arr,rem_arr)
sort_rem(trem_arr,rem_arr)
print(trem_arr,rem_arr)

错误:

Enter the number of tasks for the reminder:2
Enter the task you want to do:Eat
Enter the hour to remind you at:3
Enter the minute to remind you at:2
Enter the second to remind you at:20
Enter AM/PM:PM
Enter the task you want to do:Sleep
Enter the hour to remind you at:4
Enter the minute to remind you at:50
Enter the second to remind you at:55
Enter AM/PM:AM
['03:02:20 PM' '04:50:55 AM'] ['Eat' 'Sleep']
['03:02:20 PM' '04:50:55 AM']
['1900-01-01 15:02:20' '1900-01-01 04:50:55']
['1900-01-01 04:50:55' '1900-01-01 15:02:20']
['Sleep' 'Eat']
Traceback (most recent call last):
  File "e:\Python\ALM.py", line 73, in <module>
    sort_rem(trem_arr,rem_arr)
  File "e:\Python\ALM.py", line 28, in sort_rem
    if tr_arr[i]==dtm.strptime(a[j],"%I:%M:%S %p"):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\_strptime.py", line 349, in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data '1900-01-01 04:50:55' does not match format '%I:%M:%S %p'
PS E:\Python>

Tags: thetoinyouforlentrat
1条回答
网友
1楼 · 发布于 2024-10-01 00:31:51

首先看一下输出,您的输入仅为“h/m/s”,但您收到的日期格式为“y-m-DI:m:s”,因此问题在于更改格式。您也可以在ValueError中看到它

要更改指定格式的日期格式,您可以提供以下格式:

for i in range(len(tr_arr)):
   tr_arr[i]=dtm.strptime(tr_arr[i],"%I:%M:%S %p").strftime("%I:%M:%S %p")

要对日期时间对象的列表进行排序,可以使用列表方法sort():

tr_arr.sort()
print("sorted:",tr_arr)

相关问题 更多 >