3

For example:

I want to convert UNIX timestamps 1385629728 to str "2013-11-28 17:08:48",
and convert str "2013-11-28 17:08:48" to UNIX timestamps 1385629728.

kero
  • 10,647
  • 5
  • 41
  • 51
AlexZhang
  • 33
  • 1
  • 3
  • Please avoid asking straightforwardly google-able questions on SO. It decreases the standard of the average question. – erbdex Nov 28 '13 at 09:18

3 Answers3

4

Do it as below:

#-*-coding:utf-8-*-

import datetime, time

def ts2string(ts, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.fromtimestamp(ts)
    return dt.strftime(fmt)

def string2ts(string, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.strptime(string, fmt)
    t_tuple = dt.timetuple()
    return int(time.mktime(t_tuple))

def test():
    ts = 1385629728

    string = ts2string(ts)
    print string

    ts = string2ts(string)
    print ts

if __name__ == '__main__':
    test()
Yarkee
  • 9,086
  • 5
  • 28
  • 29
2

You should use datetime.

>>> import datetime
>>> print(datetime.datetime.fromtimestamp(int("1385629728")).strftime('%Y-%m-%d %H:%M:%S'))
2013-11-28 14:38:48
>>> print int(datetime.datetime.strptime('2013-11-28 14:38:48', '%Y-%m-%d %H:%M:%S').strftime("%s"))
1385629728
Sudipta
  • 4,773
  • 2
  • 27
  • 42
0
import time 

# where epoch is your epoch time value 
time.strftime("%a, %d %b %Y %H:%M:%S +0000", 
                        time.localtime(epoch))

Source

erbdex
  • 1,899
  • 3
  • 22
  • 40