简体   繁体   English

将字符串转换为datetime到epoch

[英]Convert string to datetime to epoch

I am using Python to query a MySQL table and getting one datetime in string format, which is stored in row[3] . 我使用Python查询MySQL表并以字符串格式获取一个日期时间,该日期时间存储row[3] I need to convert this string timestamp to epoch seconds. 我需要将此字符串时间戳转换为纪元秒。

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

On execution it throws this error: 执行时会抛出此错误:

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

What am I doing wrong? 我究竟做错了什么?

I have also tried the following: 我也尝试过以下方法:

epoch_start = time.mktime(time.strptime(row[3], "%Y-%m-%d %H:%M:%S"));

But I get this error: 但我得到这个错误:

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

The value in row[3] is already in the datetime.datetime format as it is being clearly pointed out by the traceback. row [3]中的值已经是datetime.datetime格式,因为traceback清楚地指出了它。 So there is no need for creating the variable date . 因此无需创建变量日期 You can use the row[3] directly as a datetime.datetime object. 您可以直接将行[3]用作datetime.datetime对象。

Just try printing: 试试打印:

print type(row[3])

That should give the type as datetime.datetime 这应该将类型赋予datetime.datetime

row[3] is already in datetime.datetime format.

From your question its sounds like you want convert to EPOCH so do something like: 根据你的问题,它听起来像你想要转换为EPOCH所以做类似的事情:

import time
epochTime = time.mktime(row[3].timetuple())
print epochTime

Then check if the converted epoch is correct or not: 然后检查转换的纪元是否正确:

print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epochTime))
print row[3]

Verify last two statements have the same output. 验证最后两个语句是否具有相同的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM