![](/img/trans.png)
[英]Get File's Epoch timestamp, convert to DateTime, to string, and then to the identical epoch float with microsecond precision
[英]Convert string to datetime to epoch
我使用Python查詢MySQL表並以字符串格式獲取一個日期時間,該日期時間存儲row[3]
。 我需要將此字符串時間戳轉換為紀元秒。
import MySQLdb
import os
import datetime
try:
db = MySQLdb.connect("localhost","root","","test" )
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
cursor = db.cursor()
cursor.execute ("SELECT * from main_tbl WHERE login_user_name='kumar'")
data = cursor.fetchall()
for row in data :
print row[3] ###printing 2014-09-26 12:24:23
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
print date
執行時會拋出此錯誤:
2014-09-26 12:24:23
Traceback (most recent call last):
File "test1.py", line 22, in <module>
date = datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S")
TypeError: must be string, not datetime.datetime
我究竟做錯了什么?
我也嘗試過以下方法:
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
但我得到這個錯誤:
Traceback (most recent call last):
File "test1.py", line 29, in <module>
epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));
File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\lib\_strptime.py", line 322, in _strptime
found = format_regex.match(data_string)
TypeError: expected string or buffer
row [3]中的值已經是datetime.datetime格式,因為traceback清楚地指出了它。 . 因此無需創建變量 。 您可以直接將行[3]用作datetime.datetime對象。
試試打印:
print type(row[3])
這應該將類型賦予datetime.datetime
row[3] is already in datetime.datetime format.
根據你的問題,它聽起來像你想要轉換為EPOCH
所以做類似的事情:
import time
epochTime = time.mktime(row[3].timetuple())
print epochTime
然后檢查轉換的紀元是否正確:
print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime))
print row[3]
驗證最后兩個語句是否具有相同的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.