最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

python ,use function timestamp() ,cause error Invalid argument - Stack Overflow

matteradmin19PV0评论

I want to extract two keywords of interest from a log file and calculate the time difference between them. Each line in the log starts with a timestamp in the following format. For example, I want to calculate the duration between the keywords abc and def.

01-20 09:18:42.637   721  4768 I abc : START a 
01-20 09:18:43.968   721   777 I hhhhh : fffffff
01-20 09:19:02.886 11719 11864 D def :end cccc

duration_List.append(float("%.3f" % (start_time.timestamp() - start_time.timestamp()))) ^^^^^^^^^^^^^^^^^^^^^^ OSError: [Errno 22] Invalid argumen

my code is

def Get_Line_Time_s(line):
    time_format = "%m-%d %H:%M:%S.%f"
    dt = datetime.strptime(line[:18], time_format)
    return dt  

def Calculate_Time(logcat_file, keyword_start, keyword_end):
    cmd = "grep -aEi '%s|%s' %s" % (keyword_start, keyword_end, logcat_file)
    print("\n Using command: %s" % cmd)
    tmp_file = TEMP_FILE
    if os.path.exists(tmp_file):
        os.remove(tmp_file)    

    with open(tmp_file, "w") as tmp:
        subprocess.run(["bash", "-c", cmd], stdout=tmp)
    tmp.close()
    logs = open(tmp_file, "r")
    read_lines = logs.readlines()

    duration_List = []
    pre_line = None
    for line in read_lines:
        if line.find(keyword_end) != -1 and pre_line != None:
            end_time = Get_Line_Time_s(line)
            print(end_time)
            start_time = Get_Line_Time_s(pre_line)
            duration_List.append(float("%.3f" % (end_time.timestamp() - start_time.timestamp())))
        pre_line = line

    logs.close()
    return duration_List

I am a new Python programmer, and I encountered this error but don’t know how to troubleshoot it. Could you please provide some guidance and help? Thank you very much!

It fixed by change code as follows @Vũ Trí Anh Hoàng

def Get_Line_Time_s(line):
    time_format = "%m-%d %H:%M:%S.%f"
    dt = datetime.strptime(line[:18], time_format)
    current_year = datetime.now().year
    dt = dt.replace(year=2025)
    return dt  

I want to extract two keywords of interest from a log file and calculate the time difference between them. Each line in the log starts with a timestamp in the following format. For example, I want to calculate the duration between the keywords abc and def.

01-20 09:18:42.637   721  4768 I abc : START a 
01-20 09:18:43.968   721   777 I hhhhh : fffffff
01-20 09:19:02.886 11719 11864 D def :end cccc

duration_List.append(float("%.3f" % (start_time.timestamp() - start_time.timestamp()))) ^^^^^^^^^^^^^^^^^^^^^^ OSError: [Errno 22] Invalid argumen

my code is

def Get_Line_Time_s(line):
    time_format = "%m-%d %H:%M:%S.%f"
    dt = datetime.strptime(line[:18], time_format)
    return dt  

def Calculate_Time(logcat_file, keyword_start, keyword_end):
    cmd = "grep -aEi '%s|%s' %s" % (keyword_start, keyword_end, logcat_file)
    print("\n Using command: %s" % cmd)
    tmp_file = TEMP_FILE
    if os.path.exists(tmp_file):
        os.remove(tmp_file)    

    with open(tmp_file, "w") as tmp:
        subprocess.run(["bash", "-c", cmd], stdout=tmp)
    tmp.close()
    logs = open(tmp_file, "r")
    read_lines = logs.readlines()

    duration_List = []
    pre_line = None
    for line in read_lines:
        if line.find(keyword_end) != -1 and pre_line != None:
            end_time = Get_Line_Time_s(line)
            print(end_time)
            start_time = Get_Line_Time_s(pre_line)
            duration_List.append(float("%.3f" % (end_time.timestamp() - start_time.timestamp())))
        pre_line = line

    logs.close()
    return duration_List

I am a new Python programmer, and I encountered this error but don’t know how to troubleshoot it. Could you please provide some guidance and help? Thank you very much!

It fixed by change code as follows @Vũ Trí Anh Hoàng

def Get_Line_Time_s(line):
    time_format = "%m-%d %H:%M:%S.%f"
    dt = datetime.strptime(line[:18], time_format)
    current_year = datetime.now().year
    dt = dt.replace(year=2025)
    return dt  
Share Improve this question edited Jan 21 at 8:51 morty morty asked Jan 21 at 8:06 morty mortymorty morty 196 bronze badges 13
  • Your indents is confusing. Please take the time to format your code as it is on your system and include the full traceback error. If the code is as-is your code, then you have an indentation issue. – ewokx Commented Jan 21 at 8:11
  • Can you share what start_time and end_time are? – Mureinik Commented Jan 21 at 8:13
  • 1 You can't possibly get an OSError from a float cast. – AKX Commented Jan 21 at 8:13
  • 1 @ewokx I have updte the full code – morty morty Commented Jan 21 at 8:28
  • 1 @globglogabgalab I passed string 01-20 09:19:02.886 11719 11864 D hh kkk and add print(end_time) to print it . the output is 1900-01-20 09:19:02.886000 I don't know why it print 1900 ? – morty morty Commented Jan 21 at 8:28
 |  Show 8 more comments

1 Answer 1

Reset to default 1

Because you don't have year in your datetime object

from datetime import datetime

time_str = "01-21 15:30:45.123456"
time_format = "%m-%d %H:%M:%S.%f"

dt = datetime.strptime(time_str, time_format)
new_dt = dt.replace(year=2025)

print(new_dt.timestamp()) # 1737448245.123456
print(dt.timestamp()) # Error Invalid argument
Post a comment

comment list (0)

  1. No comments so far