Search code examples
pythondatetimeutc

Convert to UTC Timestamp


# parses some string into that format.
datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")

# gets the seconds from the above date.
timestamp1 = time.mktime(datetime1.timetuple())

# adds milliseconds to the above seconds.
timeInMillis = int(timestamp1) * 1000

How do I (at any point in that code) turn the date into UTC format? I've been ploughing through the API for what seems like a century and cannot find anything that I can get working. Can anyone help? It's currently turning it into Eastern time i believe (however I'm in GMT but want UTC).

EDIT: I gave the answer to the guy with the closest to what I finally found out.

datetime1 = datetime.strptime(somestring, someformat)
timeInSeconds = calendar.timegm(datetime1.utctimetuple())
timeInMillis = timeInSeconds * 1000

:)


Solution

  • def getDateAndTime(seconds=None):
     """
      Converts seconds since the Epoch to a time tuple expressing UTC.
      When 'seconds' is not passed in, convert the current time instead.
      :Parameters:
          - `seconds`: time in seconds from the epoch.
      :Return:
          Time in UTC format.
    """
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))`
    

    This converts local time to UTC

    time.mktime(time.localtime(calendar.timegm(utc_time)))
    

    http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

    If converting a struct_time to seconds-since-the-epoch is done using mktime, this conversion is in local timezone. There's no way to tell it to use any specific timezone, not even just UTC. The standard 'time' package always assumes that a time is in your local timezone.