IT박스

MySQL에 Python datetime.datetime 객체 삽입

itboxs 2020. 8. 9. 10:15
반응형

MySQL에 Python datetime.datetime 객체 삽입


MySQL 테이블에 날짜 열이 있습니다. datetime.datetime()이 열에 개체 를 삽입하고 싶습니다 . execute 문에서 무엇을 사용해야합니까?

나는 시도했다 :

now = datetime.datetime(2009,5,5)

cursor.execute("INSERT INTO table
(name, id, datecolumn) VALUES (%s, %s
, %s)",("name", 4,now))

다음과 같은 오류가 발생합니다. "TypeError: not all arguments converted during string formatting"대신 무엇을 사용해야 %s합니까?


시간 필드의 경우 다음을 사용하십시오.

import time    
time.strftime('%Y-%m-%d %H:%M:%S')

strftime은 datetime에도 적용된다고 생각합니다.


datecolumn 값 주위에 따옴표가 필요하기 때문에 TypeError가 발생할 가능성이 높습니다.

시험:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

형식과 관련하여 위의 명령 (밀리 초 포함)과 다음을 사용하여 성공했습니다.

now.strftime('%Y-%m-%d %H:%M:%S')

도움이 되었기를 바랍니다.


대신을 사용하여 객체 now.date()를 얻으십시오 .DateDateTime

작동하지 않으면 문자열로 변환하면 작동합니다.

now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))

어떤 데이터베이스에 연결하고 있습니까? Oracle은 날짜 형식에 대해 까다로울 수 있으며 ISO 8601 형식을 좋아 합니다.

** 참고 : 죄송합니다. MySQL을 사용 중이라고 읽었습니다. 날짜 형식을 지정하고 테스트를위한 별도의 직접 SQL 호출로 시도하십시오.

Python에서는 다음과 같은 ISO 날짜를 얻을 수 있습니다.

now.isoformat()

예를 들어 오라클은 다음과 같은 날짜를 좋아합니다.

insert into x values(99, '31-may-09');

데이터베이스에 따라 Oracle 인 경우 TO_DATE해야 할 수 있습니다.

insert into x
values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));

TO_DATE의 일반적인 사용법은 다음과 같습니다.

TO_DATE(<string>, '<format>')

다른 데이터베이스를 사용하는 경우 (커서를보고 Oracle이라고 생각했습니다. 틀릴 수 있음) 날짜 형식 도구를 확인하십시오. MySQL의 경우 DATE_FORMAT ()이고 SQL Server는 CONVERT입니다.

또한 SQLAlchemy 와 같은 도구를 사용하면 이와 같은 차이점이 제거되고 생활이 쉬워집니다.


Python 메서드를 사용 datetime.strftime(format)합니다 '%Y-%m-%d %H:%M:%S'. 여기서 format = .

import datetime

now = datetime.datetime.utcnow()

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
               ("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))

시간대

If timezones are a concern, the MySQL timezone can be set for UTC as follows:

cursor.execute("SET time_zone = '+00:00'")

And the timezone can be set in Python:

now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

MySQL Documentation

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.


If you're just using a python datetime.date (not a full datetime.datetime), just cast the date as a string. This is very simple and works for me (mysql, python 2.7, Ubuntu). The column published_date is a MySQL date field, the python variable publish_date is datetime.date.

# make the record for the passed link info
sql_stmt = "INSERT INTO snippet_links (" + \
    "link_headline, link_url, published_date, author, source, coco_id, link_id)" + \
    "VALUES(%s, %s, %s, %s, %s, %s, %s) ;"

sql_data = ( title, link, str(publish_date), \
             author, posted_by, \
             str(coco_id), str(link_id) )

try:
    dbc.execute(sql_stmt, sql_data )
except Exception, e:
    ...

when iserting into t-sql

this fails:

select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)

this works:

select CONVERT(datetime,'2019-09-13 09:04:35.823',21)

easy way:

regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)

참고URL : https://stackoverflow.com/questions/1136437/inserting-a-python-datetime-datetime-object-into-mysql

반응형