Python:INPUT一个microtime float,RESULT一个格式化的日期时间

2 python floating-point time datetime

我对Python时间和日期时间方法很困惑.有人可以帮帮我吗?

我只想实现从microtime Float到这种格式的格式化字符串的转换:

mt = 1342993416.0
start_time_format = '%Y-%m-%d %H:%M:%S'

// Some time or datetime magic here..

OUTPUT >> The file's date is: 2012-07-23 19:00:00
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

使用 .fromtimestamp()类方法:

>>> import datetime
>>> mt = 1342993416.0
>>> datetime.datetime.fromtimestamp(mt)
datetime.datetime(2012, 7, 22, 23, 43, 36)
Run Code Online (Sandbox Code Playgroud)

然后使用该strftime方法格式化输出:

>>> start_time_format = '%Y-%m-%d %H:%M:%S'
>>> datetime.datetime.fromtimestamp(mt).strftime(start_time_format)
'2012-07-22 23:43:36'
Run Code Online (Sandbox Code Playgroud)

你也可以使用这个time.strftime功能:

>>> import time
>>> time.strftime(start_time_format, time.localtime(mt))
'2012-07-22 23:43:36'
Run Code Online (Sandbox Code Playgroud)