Archive

Posts Tagged ‘timestamp’

UTC now → timestamp → UTC time

January 25, 2015 2 comments

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: , , ,

Current date and time

February 25, 2011 Leave a comment
#!/usr/bin/env python

from datetime import datetime

now = datetime.now()
date = datetime.date(now)
time = datetime.time(now)
print "%d-%02d-%02d @ %02dh%02d" % (date.year, date.month, date.day, time.hour, time.minute)

Sample output:

2011-02-25 @ 11h23

Update (20110523)
I wanted to use a timestamp in the name of a temporary file. Here is a slightly modified version of the code above:

...
print "{year}{month:02}{day:02}_{hour:02}{minute:02}{second:02}".format(year=date.year, month=date.month, day=date.day, hour=time.hour, minute=time.minute, second=time.second)
...

Sample output:

20110523_235828
Categories: python Tags: , , ,