2017-02-09 105 views
0

我收到日期對象:毫秒到字符串/日期格式

now = datetime.utcnow() 
print(now) 

2017-02-09 14:00:31.256382 

然後,使得字符串表示:

to_string = now.strftime("%Y-%m-%d %H:%M:%S.%f") 
print(to_string) 

2017-02-09 14:00:31.256382 (it is a str object) 

我把它轉換成秒:

sec = now.replace(tzinfo=timezone.utc).timestamp() 
print(sec) 

1486648831.256382 

1)我試圖找回字符串表示法:

back = time.strftime("%Y-%m-%d %H:%M:%S.%f", time.gmtime(x)) 
print(back) 

2017-02-09 14:00:31.%f 

我無法確定如何表示毫秒。注意,timestamp也表示返回秒數而不是毫秒。 2)如果我想從秒(或在我的情況下毫秒)回到日期對象而不是字符串對象?

+0

有關的字符串表示MS:我想你想'now.strftime(「%Y-%間%d%H:%M:%S.% f「)'而不是'time.strftime' –

回答

3

使用utcfromtimestamp方法。

from datetime import datetime 

ts = 1486648831.256382 
print (datetime.utcfromtimestamp(ts)) 
>>> 2017-02-09 14:00:31.256382 

類方法datetime.utcfromtimestamp(時間戳)

返回對應於POSIX時間戳,與 tzinfo儘管如此UTC日期時間。如果時間戳超出平臺C gmtime()函數支持的值的 範圍,則這可能會引發ValueError。它的 通常會限制在1970年到2038年。請參閱 也是從timestamp()開始的。

返回的對象是<class 'datetime.datetime'>

+0

好的,謝謝!至於毫秒,時間戳返回秒並不重要,因爲您可以根據需要表示字符串,對嗎? – George

+0

@George,這是正確的。 –