Convert UNIX timestamp to str and str to UNIX timestamp in python

python

Solution

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()

Problem

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`.

Original source

Related problems