assigning dates using regex, converting them with strptime and then applying to dataframe using lambda. Code works but pytest is failing?

huangapple go评论77阅读模式
英文:

assigning dates using regex, converting them with strptime and then applying to dataframe using lambda. Code works but pytest is failing?

问题

I was wondering if i could get some help on this code? The function is assigning dates using regex, converting them with strptime and then applying to dataframe using lambda. Code works but pytest is failing and i have no idea why?

Here is the code for you to look at:

from datetime import datetime, date
import re
import pandas as pd


def conv_date(dte: str) -> date:
    acceptable_mappings = {
        "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}": "%Y-%m-%d %H:%M:%S",

    }

    for regex in acceptable_mappings.keys():
        if re.fullmatch(regex, dte):
            return datetime.strptime(dte, acceptable_mappings[regex]).date()
    raise Exception(f"Expected date in one of supported formats, got {dte}")


def full_list_parse(unclean_list: list) -> list:
    return [conv_date(dte) for dte in unclean_list]


mock_dict = [
    {"name": "xx", "role": "loves only-fans", "date": "2023-07-26 12:46:21"},

]

df = pd.DataFrame(mock_dict)

if __name__ == "__main__":
    print(df)
    df['date_clean'] = df['date'].apply(lambda x: conv_date(x))
    print(df)

When i run the above code i get back which is desired. The date to be converted to 2023-07-26:

  name             role                 date
0   xx  loves only-fans  2023-07-26 12:46:21
  name             role                 date  date_clean
0   xx  loves only-fans  2023-07-26 12:46:21  2023-07-26

And here is my test:

from x import *
import pytest


class TestConvDate:
    classical_programming_with_datetime = "2023-07-26 12:46:21"

    def test_classical_programming_with_datetime(self):
        assert datetime(2023, 7, 26) == conv_date(self.classical_programming_with_datetime)

    def test_error_is_raised(self):
        with pytest.raises(Exception):
            conv_date("some issue")

But when i run this test, i get this error!

Expected :datetime.date(2023, 7, 26)
Actual   :datetime.datetime(2023, 7, 26, 0, 0)

Do I need to assert differently, i thought my function handles the time portion of the datetime? Where are these zeros coming from? I tried changing the assert to:

assert datetime(2023, 7, 26, 0, 0) == conv_date(self.classical_programming_with_datetime)

but im still getting the same error!
Any ideas?

Thanks

英文:

I was wondering if i could get some help on this code? The function is assigning dates using regex, converting them with strptime and then applying to dataframe using lambda. Code works but pytest is failing and i have no idea why?

Here is the code for you to look at:

from datetime import datetime, date
import re
import pandas as pd


def conv_date(dte: str) -> date:
    acceptable_mappings = {
        "\d{4}-\d{2}-\d{2}\s\d{2}\:\d{2}\:\d{2}": "%Y-%m-%d %H:%M:%S",

    }

    for regex in acceptable_mappings.keys():
        if re.fullmatch(regex, dte):
            return datetime.strptime(dte, acceptable_mappings[regex]).date()
    raise Exception(f"Expected date in one of supported formats, got {dte}")


def full_list_parse(unclean_list: list) -> list:
    return [conv_date(dte) for dte in unclean_list]


mock_dict = [
    {"name": "xx", "role": "loves only-fans", "date": "2023-07-26 12:46:21"},

]

df = pd.DataFrame(mock_dict)

if __name__ == "__main__":
    print(df)
    df['date_clean'] = df['date'].apply(lambda x: conv_date(x))
    print(df)

When i run the above code i get back which is desired. The date to be converted to 2023-07-26:

  name             role                 date
0   xx  loves only-fans  2023-07-26 12:46:21
  name             role                 date  date_clean
0   xx  loves only-fans  2023-07-26 12:46:21  2023-07-26

And here is my test:

from x import *
import pytest


class TestConvDate:
    classical_programming_with_datetime = "2023-07-26 12:46:21"

    def test_classical_programming_with_datetime(self):
        assert datetime(2023, 7, 26) == conv_date(self.classical_programming_with_datetime)

    def test_error_is_raised(self):
        with pytest.raises(Exception):
            conv_date("some issue")

But when i run this test, i get this error!

Expected :datetime.date(2023, 7, 26)
Actual   :datetime.datetime(2023, 7, 26, 0, 0)

Do I need to assert differently, i thought my function handles the time portion of the datetime? Where are these zeros coming from? I tried changing the assert to:

assert datetime(2023, 7, 26, 0, 0) == conv_date(self.classical_programming_with_datetime)

but im still getting the same error!
Any ideas?

Thanks

答案1

得分: 1

如错误消息中所提到的,您将Dataframe中的日期转换为datetime.date类型,然后在datetime.datetime上进行断言,这是不同的类型,额外的零是小时和分钟。

为什么不只断言datetime.date

def test_classical_programming_with_datetime(self):
    assert date(2023, 7, 26) == conv_date(self.classical_programming_with_datetime)
英文:

As mentioned in the error you converted the date in the Dataframe to datetime.date type and you asserting on datetime.datetime which is a different one, the extra zeros are hours and minutes

Why not just assert on datetime.date ?

def test_classical_programming_with_datetime(self):
        assert date(2023, 7, 26) == conv_date(self.classical_programming_with_datetime)

huangapple
  • 本文由 发表于 2023年7月31日 19:54:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76803356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定