如何使用“获取当前日期”从文件中查找日期和数字?

问题描述 投票:0回答:2

我有一个文件,dates.txt,其中包含 dd.mm.yyyy 格式的日期,旁边有一个数字,现在我需要只返回正确日期的数字。我使用“获取当前日期”,例如,在 2023 年 8 月 15 日,我需要机器人抓取旁边的 44253。有什么建议吗?

我试图寻找答案,但找不到适合我需求的答案。

编辑:固定示例,8-> 08,添加信息,并稍微清理了问题。

dates.txt中的数据是这样的

08.05.2024     608243
09.05.2024     323409
10.05.2024     934510
11.05.2024     637343

日期,以及数字前的几个空格。文件本身并不是太重要,所以可以进行更改,只要我能在正确的日期获得号码即可。

仅在Robot Framework中寻找解决方案。

automated-tests robotframework return-value
2个回答
0
投票

您有一个包含日期和后面数字的文件dates.txt,然后您可以打开datetime模块并使用strftime来获取与dates.txt中的日期类似的今天日期,然后您可以打开文件并使用每行一个循环并检查它是否与您当前的日期匹配,如果它与当前日期匹配,那么您将获得整行并在之后使用切片来获得该数字。

from datetime import datetime
today = datetime.today().strftime("%d.%m.%Y")
whole_line = ""
dates_file = open("dates.txt" , "r")
for date in dates_file:
    if today in date:
        whole_line = date
        break # use break to not loop any further after you got the line
dates_file.close() # never forget to close your file after opening it


0
投票

这样的东西应该有效

*** Settings ***
Library    DateTime
Library    OperatingSystem
Library    String

*** Test Cases ***
DemoCase
    ${number}    Get Todays Number

*** Keywords ***
Get Todays Number
    ${dates}    Get File    dates.txt
    ${now}    Get Current Date    result_format=%d.%m.%Y
    ${lines}    Split To Lines    ${dates}
    FOR    ${line}    IN    @{lines}
        ${date}    ${right}    Split String    ${line}    ${SPACE}    max_split=1
        IF    "${date}" == "${now}"
            ${number}    Set Variable    ${right.strip()}
            RETURN    ${number}
        END
    END
    Fail    Was not able to find number for "${now}"
© www.soinside.com 2019 - 2024. All rights reserved.