python 时间判断问题

我想通过通过文件更新时间与系统时间比较 复制文件

发现我建立的时间段或设定当日日期加固定小时分 都不能复制正确文件

today_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '15:00', '%Y-%m-%d%H:%M')
create_time = os.path.getctime(filename)
create_time =time.strpmm("%Y-%M-%d %H:%M")

if (create_time)>str(file_time):
  copy("sorce"......tarket")
代码简单写下 我判断后 结果文件夹中从1点到21点所有文件都被复制 不知什么原因,未报任何错误。

我只想复制每天15点后的文件 谢谢

题主的问题不在代码而在逻辑。逻辑问题有三个:1. 应该判断文件而不是文件夹的创建时间(上面的代码获取的是文件夹的创建时间);2. 是否复制文件和日期无关,只需要小时、分钟等,无需从哪里提取,而是客观存在;3. 以复制15:30之后的文件为例,解读出文件的创建钟点数ch、分钟数cm后,判断条件是ch>16 or ch==15 and cm>30

你用datetime类型比较。别用字符串去比较。

读取文件创建时间,得到时间戳,变成struct_time,直接获取钟点数,大于15即是楼主所需的。刚生成一个文件,测试了一下,so easy

>>> import os, time
>>> ct = os.path.getctime(r'd:\demo.txt')
>>> ct_h = time.localtime(ct).tm_hour # 文件创建的钟点
>>> ct_h
15

 

我不转成str,他现在是struct_time 怎样才能转成datetime呢.用datetime.datetime.strptime() 方法 也不能比较.怎样将文件时间转成可以比较用类型?

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

謝謝 不过我试验过只是取出小时,我之前的代码时小时分钟,怎样加入分钟一起处理呢?还有我的系统比较时间是当天15:30 是datetime格式,我转成int 报错不能比较。你有解决方法?可私信wechat 付费

謝謝 不过我试验过只是取出小时,我之前的代码时小时分钟,怎样加入分钟一起处理呢?还有我的系统比较时间是当天15:30 是datetime格式,我转成int 报错不能比较。你有解决方法?可私信wechat 付费

d_time = datetime.datetime.strptime(str(datetime.datetime.now().date())+'15:30','%Y-%m-%d%H:%M')

print("d_time",d_time)
print("d_time",type(d_time))
# now_20=datetime.datetime.now() - timedelta(hours=17)
# print("now_20",now_20)

if not os.path.exists(toPath):
    os.mkdir(Guest)
    
if os.path.exists(dirPath):
    for file in os.listdir(dirPath):
        if os.path.isfile(dirPath+'/'+file):
            if key in file:
                create_time=os.path.getmtime(dirPath)
                file_time=time.localtime(create_time).tm_hour
                print("create_time",create_time)
                # filedate=time.strftime("%H:%M:%S",file_time)
                print("file_time",file_time)
                print("file_time",type(file_time))
                # a=str(filedate)
                # b=str(d_time)
                # print("a",a)
                # print("b",b)# if str(filedate)>(now_20):
                  
                 # if file_time>d_time:
if file_time in int(d_time): 

                # if "15:30:00"filedate>"18:30:00":
                    # copy2(dirPath+'/'+file, toPath+'/'+file)
                    
                    print("copy2 succiss")
                   
                    print("d_time",d_time)
else:
                    print("no match data")
  file_time <class 'int'>
create_time 1623311253.2392156
file_time 15
file_time <class 'int'>
  
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime'