Python: Converting string to timestamp with microseconds

前端 未结 3 1778
南旧
南旧 2020-12-31 10:32

I would like to convert string date format to timestamp with microseconds I try the following but not giving expected result:

\"\"\"input string date ->          


        
3条回答
  •  一整个雨季
    2020-12-31 11:25

    Where did the milliseconds go?

    It is the easy part. .timetuple() call drops them. You could add them back using .microsecond attribute. The datetime.timestamp() method from the standard library works that way for naive datetime objects:

    def timestamp(self):
        "Return POSIX timestamp as float"
        if self._tzinfo is None:
            return _time.mktime((self.year, self.month, self.day,
                                 self.hour, self.minute, self.second,
                                 -1, -1, -1)) + self.microsecond / 1e6
        else:
            return (self - _EPOCH).total_seconds()
    

    It is enough if possible ~1 hour errors could be ignored in your case. I assume that you want microseconds and therefore you can't ignore ~1 hour time errors silently.

    To convert the local time given as a string to the POSIX timestamp correctly is a complex task in general. You could convert the local time to UTC and then get the timestamp from UTC time.

    There are two main issues:

    • local time may be non-existent or ambiguous e.g. during DST transitions the same time may occur twice
    • UTC offset for the local timezone may be different in the past and therefore a naive: local time minus epoch in local time formula may fail

    Both can be solved using the tz database (pytz module in Python):

    from datetime import datetime
    import pytz # $ pip install pytz
    from tzlocal import get_localzone # $ pip install tzlocal
    
    tz = get_localzone() # get pytz timezone corresponding to the local timezone
    
    naive_d = datetime.strptime(myDate, "%Y-%m-%d %H:%M:%S,%f")
    # a) raise exception for non-existent or ambiguous times
    d = tz.localize(naive_d, is_dst=None)
    ## b) assume standard time, adjust non-existent times
    #d = tz.normalize(tz.localize(naive_d, is_dst=False))
    ## c) assume DST is in effect, adjust non-existent times
    #d = tz.normalize(tz.localize(naive_d, is_dst=True))
    timestamp = d - datetime(1970, 1, 1, tzinfo=pytz.utc)
    

    The result is timestamp -- a timedelta object, you can convert it to seconds, milliseconds, etc.

    Also different systems may behave differently around/during leap seconds. Most application can ignore that they exist.

    In general, it might be simpler to store POSIX timestamps in addition to the local time instead of trying to guess it from the local time.

提交回复
热议问题