Converting datetime to POSIX time

后端 未结 6 1903
忘了有多久
忘了有多久 2021-01-31 02:14

How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don\'t seem to find any obv

6条回答
  •  日久生厌
    2021-01-31 02:22

    It depends

    Is your datetime object timezone aware or naive?

    Timezone Aware

    If it is aware it's simple

    from datetime import datetime, timezone
    aware_date = datetime.now(tz=timezone.utc)
    posix_timestamp = aware_date.timestamp()
    

    as date.timestamp() gives you "POSIX timestamp"

    NOTE: more accurate to call it an epoch/unix timestamp as it may not be POSIX compliant

    Timezone Naive

    If it's not timezone aware (naive), then you'd need to know what timezone it was originally in so we can use replace() to convert it into a timezone aware date object. Let's assume that you've stored/retrieved it as UTC Naive. Here we create one, as an example:

    from datetime import datetime, timezone
    naive_date = datetime.utcnow()  # this date is naive, but is UTC based
    aware_date = naive_date.replace(tzinfo=timezone.utc)  # this date is no longer naive
    
    # now we do as we did with the last one
    
    posix_timestamp = aware_date.timestamp()
    

    It's always better to get to a timezone aware date as soon as you can to prevent issues that can arise with naive dates (as Python will often assume they are local times and can mess you up)

    NOTE: also be careful with your understanding of the epoch as it is platform dependent

提交回复
热议问题