0

I have unix command

echo 1378312014 | xargs -L 1 -I '{}' date -d "@{}" "+%d-%m-%Y-%H-%M"

equivalent output is 04-09-2013-17-26

Is there any python in build library that can convert 1378312014 to 04-09-2013-17-26

I am completely new to python, but I don't want to use os.popen or subprocess because they are running unix commands. I want to know if I can do it in python datetime library.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
nutim
  • 169
  • 3
  • 15
  • 1
    similar: http://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date-in-python – Ben Jun 15 '14 at 22:14

2 Answers2

2

Use datetime.datetime.fromtimestamp() to convert a UNIX timestamp to a datetime object:

dt = datetime.datetime.fromtimestamp(1378312014)
print dt.strftime('%d-%m-%Y-%H-%M')

The datetime.datetime.strftime() formats the object as a string with a desired format.

Demo:

>>> import datetime
>>> dt = datetime.datetime.fromtimestamp(1378312014)
>>> dt
datetime.datetime(2013, 9, 4, 17, 26, 54)
>>> print dt.strftime('%d-%m-%Y-%H-%M')
04-09-2013-17-26
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You can use the time module too:

 import time
 time.strftime("%d-%m:%Y-%H-%M", time.localtime(1378312014))
RohitJ
  • 543
  • 4
  • 8