Home > python > UTC now → timestamp → UTC time

UTC now → timestamp → UTC time

Problem
Say you have an application and you want to store the date/time of an event. Later you want to see this date/time.

Solution
Take the current UTC date/time and convert it to a timestamp, which is an integer. Store this value. Then read it and convert it back to UTC date/time.

>>> import datetime
>>>
>>> utcnow = datetime.datetime.utcnow()
>>> utcnow
datetime.datetime(2015, 1, 25, 18, 10, 41, 803198)
>>> ts = int(utcnow.timestamp())
>>> ts
1422205841
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2015, 1, 25, 18, 10, 41)
>>>
Categories: python Tags: , , ,
  1. April 7, 2016 at 21:44

    thanks!!!

  2. April 7, 2016 at 21:49

    i get `’datetime.datetime’ object has no attribute ‘timestamp’`

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: