Converting datetime.date to UTC timestamp in Python

Converting datetime.date to UTC timestamp in Python

Asked on November 12, 2018 in Python.
Add Comment


  • 3 Answer(s)

    For operating system systems only:

    >>> import datetime
    >>> d = datetime.date(2011,01,01)
    >>> d.strftime("%s") # <-- this can be THE CODE YOU WANT
    '1293832800'
    
    Answered on November 12, 2018.
    Add Comment

    Assumption 1: you are making an attempt to convert a date to a timestamp, but since a date covers a twenty four hour amount, there’s not one timestamp that represents that date. i am going to assume that you simply need to represent the timestamp of that date in the dark (00:00:00.000).

    Assumption 2: The date you gift isn’t related to a selected geographical zone, but you wish to see the offset from a selected geographical zone (UTC). while not knowing the geographical zone the date is in, it is not potential to calculate a timestamp for a particular geographical zone. i am going to assume that you simply need to treat the date as if it’s within the native system geographical zone.

    First, you’ll be able to convert the date instance into a tuple representing the assorted time parts mistreatment the timetuple() member:

    dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
    

    Then convert that into a timestamp using time.mktime:

    ts = time.mktime(dtt) # 1293868800.0
    

    By verifying this method by testing it with the epoch time itself (1970-01-01), during which case the operate ought to come the timezone offset for the time zone on it date:

    d = datetime.date(1970,1,1)
    dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
    ts = time.mktime(dtt) # 28800.0
    

    28800.0 is eight hours, which might be correct for the PST zone (where i am at).

    Answered on November 12, 2018.
    Add Comment

    By following the python2.7 document, In this use calendar.timegm() rather than time.mktime()

    >>> d = datetime.date(2011,01,01)
    >>> datetime.datetime.utcfromtimestamp(calendar.timegm(d.timetuple()))
    datetime.datetime(2011, 1, 1, 0, 0)
    
    Answered on November 12, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.