Search code examples
python-3.xtimestampprotocol-bufferstimestamp-with-timezone

How to add timezone and day light saving info into google protobuf Timestamp?


I'm using google protobuf timestamp for recording purpose in python, however, when I compare the timestamp, I would need to know the timezone and day light saving information associated with every timestamp. Is there any good way to do that? Thanks!


Solution

  • Timestamp's represent "point in time independent of any time zone or calendar".

    Many of the languages that implement Protobufs also provide an implementation for Timestamp (e.g. Go's `timestamppb') that includes language-specific methods to convert to/from the language's datetimes and these can be then be used for language-specific time comparisons etc.

    Worst case (if you can't use the language-specific implementations described above), you can compare the Timestamp's seconds and then nanoseconds values to order (e.g. before|after).

    The documentation provides a Python example (see "Example 5").

    Alternatively:

    from google.protobuf.timestamp_pb2 import Timestamp
    
    import datetime
    
    dt = datetime.datetime.utcnow()
    
    ts = Timestamp()
    ts.FromDatetime(dt)
    
    print(ts)
    print(ts.ToDatetime())
    print(ts.ToJsonString())
    

    Both examples depend on using protobuf