Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a epoch timestamp to yyyy/mm/dd hh:mm

I'm given a timestamp (time since the epoch) and I need to convert it into this format:

yyyy/mm/dd hh:mm

I looked around and it seems like everyone else is doing this the other way around (date to timestamp).

If your answer involves dateutil that would be great.

like image 227
user2465134 Avatar asked Aug 10 '16 14:08

user2465134


People also ask

How do I convert epoch to date?

Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds. myString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch.

Can you convert epoch time to date in Excel?

For example, converting from epoch time (milliseconds) to a date would be "=((((A1/1000)/60)/60)/24)+DATE(1970,1,1)".


1 Answers

Using datetime instead of dateutil:

import datetime as dt
dt.datetime.utcfromtimestamp(seconds_since_epoch).strftime("%Y/%m/%d %H:%M")

An example:

import time
import datetime as dt

epoch_now = time.time()
sys.stdout.write(str(epoch_now))
>>> 1470841955.88

frmt_date = dt.datetime.utcfromtimestamp(epoch_now).strftime("%Y/%m/%d %H:%M")
sys.stdout.write(frmt_date)
>>> 2016/08/10 15:09

EDIT: strftime() used, as the comments suggested.

like image 50
Nick Bull Avatar answered Oct 21 '22 14:10

Nick Bull