如果一个是来自os.path.getatime()
的str对象,你如何比较python中的2个日期我已将getatime()
对象剥离到月,日和年,并将其转换为日期时间对象但我抛出一个值错误。
import os
from time import ctime, strftime
import datetime
folder = r'C:\users\c\desktop\files'
today = strftime("%Y-%m-%d")
present = datetime
files = os.listdir(folder)
for file in files:
if file.endswith(".torrent"):
# Get date time from each file then join file and folder to create full path
date = ctime(os.path.getatime(os.path.join(folder, file)))
# Remove the timestamp
remove_timestamp = date.replace(date[11:19], "")
# Remove the day
new_date = remove_timestamp.replace(remove_timestamp[0:4], "")
# print(new_date)
if " " in new_date:
# Replace space with a comma
x = new_date.replace(" ", ",")
if ",," in x:
# Replace 2 commas with 1 coma
z = x.replace(",,", ",")
if "Mar" in z:
# Change month name to a number
mar = z.replace("Mar", "03")
# Problem start here
two_weeks = datetime.datetime(int(mar))
print(two_weeks)
# /Problem
if mar[4] is ",":
print(" " + mar, file)
else:
print(mar, file)
if "Feb" in z:
# Change month name to a number
feb = z.replace("Feb", "02")
if feb[4] is ",":
print(" " + feb, file)
else:
print(feb, file)
错误
C:\Python34\python.exe C:/Users/c/PycharmProjects/untitled10/main.py
03,19,2015 some_file.torrent
Traceback (most recent call last):
File "C:/Users/c/PycharmProjects/untitled10/main.py", line 30, in <module>
two_weeks = datetime.datetime(int(mar))
ValueError: invalid literal for int() with base 10: '03,19,2015'
Process finished with exit code 1
答案 0 :(得分:1)
os.path.getatime()
返回&#34;秒以来&#34;秒作为浮点数(time.time()
函数返回的值)。它是一个POSIX时间戳(&#34;自Epoch以来的秒数&#34; - 自1970-01-01 UTC以来经过的非飞跃SI秒数)在Python工作的常见系统上(除非&#34;右&#34 ;使用时区)。
要将其转换为表示UTC时间的日期时间对象,请调用datetime.utcfromtimestamp()
方法。
不要混淆对象的字符串表示和对象本身。不要将时间/日期比作字符串,而是使用对象。
from datetime import datetime, timedelta
now = datetime.utcnow()
file_time = datetime.utcfromtimestamp(os.path.getmtime(filename))
if (now - file_time) > timedelta(1):
print("more than a day has passed")
答案 1 :(得分:0)
当os.path.getatime
返回一个时间戳时,使用带有(24%3600)的模数来粗略地获得一天精度的日期并不是更好。
如果您仍想将其转换为日期字符串,请比较您可以使用time.strptime(string[, format])
的每个组件,它应该将字符串解析为日期组件的元组。