Saturday, January 31, 2015

Finding time in Python

In order to properly record the data, I need a timestamp. I found a few minutes this afternoon where I could research it a little. I found two methods:

Using datetime:
>>> from datetime import datetime
>>> current_time = datetime.now()
>>> current_time
datetime.datetime(2015, 1, 31, 15, 35, 14, 21154)

Simple. But there is one slight problem. I'm sure there's a way to do it, but how do you extract just the day, hour, our minute, without any of the other variables?

I would research this more, and probably will, except that I found another solution.
Using time:
>>> from time import strftime,gmtime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2015-01-31 20:41:22'
>>> strftime("%Y-%m-%d %H:%M:%S")
'2015-01-31 15:41:26'

In my opinion, this second option is easier. Yes, you need to know date and time codes and formats for Linux, but I've dealt with those for a while, so it shouldn't be an issue for me. For a reference, the codes are found by looking up "man date" in a terminal window in Linux.

In addition to already knowing the date codes, this method also make it possible to set my own preferences in how each timestamp is recorded.

No comments:

Post a Comment