Cory
Cory

Reputation: 15615

How to remove hours, minutes, and seconds from a Unix timestamp?

Without having to convert it to datetime, how can I get the date from a Unix timestamps? In other words, I would like to remove hours, minutes and seconds from the time stamp and get the numbers that represent the date only.

Upvotes: 2

Views: 4758

Answers (2)

Daniel t.
Daniel t.

Reputation: 1055

If running the script in a UNIX like OS, you can use the date command -

>>>import subprocess
>>>process=subprocess.Popen(['date','-d','@1430106933', '+%Y%m%d'], stdout=subprocess.PIPE)
>>>out,err = process.communicate()
>>>print out
20150426

Upvotes: 1

wim
wim

Reputation: 362746

I know you asked "without having to convert to datetime", but I really think this is the best method.

>>> t
1430103943.581003
>>> datetime.date(datetime.fromtimestamp(t)).strftime("%s")
'1430056800'

To do it manually will require knowing about all the special cases, leap years, leap seconds etc. It's impractical and all the heavy lifting has already been done for you by datetime, so why bother?

Upvotes: 3

Related Questions