- 
                Notifications
    
You must be signed in to change notification settings  - Fork 79
 
Epoch - unix timestamp #240
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 6 commits
      Commits
    
    
            Show all changes
          
          
            7 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      4942a4a
              
                Epoch - unix timestamp
              
              
                commonism 6cd0de0
              
                liniting
              
              
                commonism aa280c6
              
                epoch - split into number & integer
              
              
                commonism f9c93d1
              
                compat - 3.8 typing
              
              
                commonism efe1411
              
                typing …
              
              
                commonism 6f0b765
              
                coverage
              
              
                commonism e4becc9
              
                epoch - docs & tests
              
              
                commonism File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| from __future__ import annotations | ||
| 
     | 
||
| import datetime | ||
| from typing import Any, Callable | ||
| 
     | 
||
| import pydantic_core.core_schema | ||
| from pydantic import GetJsonSchemaHandler | ||
| from pydantic.json_schema import JsonSchemaValue | ||
| from pydantic_core import CoreSchema, core_schema | ||
| 
     | 
||
| EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) | ||
| 
     | 
||
| 
     | 
||
| class _Base(datetime.datetime): | ||
| TYPE: str = '' | ||
| SCHEMA: pydantic_core.core_schema.CoreSchema | ||
| 
     | 
||
| @classmethod | ||
| def __get_pydantic_json_schema__( | ||
| cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler | ||
| ) -> JsonSchemaValue: | ||
| field_schema: dict[str, Any] = {} | ||
| field_schema.update(type=cls.TYPE, format='date-time') | ||
| return field_schema | ||
| 
     | 
||
| @classmethod | ||
| def __get_pydantic_core_schema__( | ||
| cls, source: type[Any], handler: Callable[[Any], CoreSchema] | ||
| ) -> core_schema.CoreSchema: | ||
| return core_schema.with_info_after_validator_function( | ||
| cls._validate, | ||
| cls.SCHEMA, | ||
| serialization=core_schema.wrap_serializer_function_ser_schema(cls._f, return_schema=cls.SCHEMA), | ||
| ) | ||
| 
     | 
||
| @classmethod | ||
| def _validate(cls, __input_value: Any, _: Any) -> datetime.datetime: | ||
| return EPOCH + datetime.timedelta(seconds=__input_value) | ||
| 
     | 
||
| @classmethod | ||
| def _f(cls, value: Any, serializer: Callable[[Any], Any]) -> Any: # pragma: no cover | ||
| raise NotImplementedError(cls) | ||
| 
     | 
||
| 
     | 
||
| class Number(_Base): | ||
| TYPE = 'number' | ||
| SCHEMA = core_schema.float_schema() | ||
| 
     | 
||
| @classmethod | ||
| def _f(cls, value: Any, serializer: Callable[[float], float]) -> float: | ||
| ts = value.timestamp() | ||
| return serializer(ts) | ||
| 
     | 
||
| 
     | 
||
| class Integer(_Base): | ||
| TYPE = 'integer' | ||
| SCHEMA = core_schema.int_schema() | ||
| 
     | 
||
| @classmethod | ||
| def _f(cls, value: Any, serializer: Callable[[int], int]) -> int: | ||
| ts = value.timestamp() | ||
| return serializer(int(ts)) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import datetime | ||
| 
     | 
||
| import pytest | ||
| 
     | 
||
| from pydantic_extra_types import epoch | ||
| 
     | 
||
| 
     | 
||
| @pytest.mark.parametrize('type_,cls_', [(int, epoch.Integer), (float, epoch.Number)], ids=['integer', 'number']) | ||
| def test_type(type_, cls_): | ||
| from pydantic import BaseModel | ||
| 
     | 
||
| class A(BaseModel): | ||
| epoch: cls_ | ||
| 
     | 
||
| now = datetime.datetime.now(tz=datetime.timezone.utc) | ||
| ts = type_(now.timestamp()) | ||
| a = A.model_validate({'epoch': ts}) | ||
| v = a.model_dump() | ||
| assert v['epoch'] == ts | ||
| 
     | 
||
| b = A.model_construct(epoch=now) | ||
| 
     | 
||
| v = b.model_dump() | ||
| assert v['epoch'] == ts | ||
| 
     | 
||
| c = A.model_validate(dict(epoch=ts)) | ||
| v = c.model_dump() | ||
| assert v['epoch'] == ts | ||
| 
     | 
||
| 
     | 
||
| @pytest.mark.parametrize('cls_', [(epoch.Integer), (epoch.Number)], ids=['integer', 'number']) | ||
| def test_schema(cls_): | ||
| from pydantic import BaseModel | ||
| 
     | 
||
| class A(BaseModel): | ||
| dt: cls_ | ||
| 
     | 
||
| v = A.model_json_schema() | ||
| assert (dt := v['properties']['dt'])['type'] == cls_.TYPE and dt['format'] == 'date-time' | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.