简体   繁体   中英

Python dataclass and date issue

I have this data class in python.

from dataclasses import dataclass
from dataclasses_json import dataclass_json

    @dataclass                                 
    @dataclass_json                            
    class Test:                                
        published_date: datetime = "" 
        version: str = ""     
             

And this dictionary

row                                        
{'published_date': '', 'version': 'ver 6'} 

When i try to create the data class from the dictionary i get an error.

Test.from_dict(row)
    218     else:                                                    
    219         tz = datetime.now(timezone.utc).astimezone().tzinfo  
--> 220         res = datetime.fromtimestamp(field_value, tz=tz)     
    221 elif _issubclass_safe(field_type, Decimal):                  
    222     res = (field_value                                       
    223            if isinstance(field_value, Decimal)               
    224            else Decimal(field_value))                        
                                                                     
TypeError: 'str' object cannot be interpreted as an integer 

     

I want only the date portion of the string and not the time. Why am i getting this error ?

I changed the decorator order and surprisingly it works now.

 @dataclass_json                                                 
 @dataclass                                                      
 class Test:                                                     
     published_date: datetime.date = ""                          
     version: str = ""                                           
                                                                 
                                                                 
row = {"published_date": "", "version": ""}                      
                                                                 
Test.from_dict(row)                                              
Test(published_date='', version='')                              
                                                                 
row = {"published_date": "2022-05-17", "version": ""}            
                                                                 
Test.from_dict(row)                                              
Test(published_date='2022-05-17', version='')  

              

Another option you could look into, assuming that you don't need to work with marshmallow schemas, would be the dataclass-wizard . It should overall be slightly faster - I added a quick comparison i put together below.

from __future__ import annotations  # can be removed in Python 3.10+

import datetime
from dataclasses import dataclass
from timeit import timeit

from dataclass_wizard import JSONWizard
from dataclasses_json import dataclass_json


@dataclass_json
@dataclass
class Test:
    published_date: datetime.date = ''
    version: str = ''


@dataclass
class TestWiz(JSONWizard):
    published_date: datetime.date | str = ''
    version: str = ''


n = 1_000

row1 = {"published_date": "", "version": ""}
row2 = {"published_date": "2022-05-17", "version": ""}

tj = timeit('Test.from_dict(row1)', number=n, globals=globals())
tw = timeit('TestWiz.from_dict(row1)', number=n, globals=globals())

print(f'dataclasses-json:  {tj:.3f}')  # 0.024
print(f'dataclass-wizard:  {tw:.3f}')  # 0.001

# assert data is the same
assert Test.from_dict(row2).__dict__ == TestWiz.from_dict(row2).__dict__

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM