将Python字符串日期转换为MySQL日期时间

1 投票
2 回答
1295 浏览
提问于 2025-04-18 03:35

我有一个字符串字段,里面是从网上抓取的日期,格式是这样的:

 "Lun Ene 27, 2014 9:52 am", "Mar Feb 11, 2014 5:38 pm",...

Lun = 星期几(lunes/星期一)
Ene = 月份(enero/一月)

我需要把这些日期放进一个MySQL表格里,放在一个日期时间字段中。

'YYYY-MM-DD HH:MM:SS'

我想这应该是一个很常见的问题,所以想问问有没有人已经写过这样的脚本,或者能告诉我在哪里可以找到相关的资料……

提前谢谢大家!

2 个回答

0

默认情况下,Python使用的是C语言环境:

>>> from datetime import datetime
>>> datetime.strptime("Tue Feb 11, 2014 5:38 PM", "%a %b %d, %Y %I:%M %p")
datetime.datetime(2014, 2, 11, 17, 38)
>>> import locale
>>> locale.nl_langinfo(locale.T_FMT_AMPM)
'%I:%M:%S %p'

在我的系统上,改变语言环境部分有效:

>>> locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
'es_ES.UTF-8'
>>> datetime.strptime("Lun Ene 27, 2014 9:52 am"[:-2], "%a %b %d, %Y %I:%M %p")
datetime.datetime(2014, 1, 27, 9, 52)
>>> locale.nl_langinfo(locale.T_FMT_AMPM)
''

在我的系统中,T_FMT_AMPM没有被设置,尤其是对于es_ES.UTF-8这个语言环境。要解决这个问题,如果时间字符串以'pm'结尾,你可以手动加上12个小时。

strftime()time的表现是一样的。

注意:在其他系统上,语言环境的名称可能会有所不同。

1
month_of_the_year = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dec']

def convert_to_mysql_format(string):
  explode = string.split()
  day_of_the_month = explode[2][:-1]
  if int(explode[2][:-1]) < 10:
    day_of_the_month = "%02d" % (int(explode[2][:-1]),)

  if explode[5] == 'am':
    time_split = explode[4].split(':')
    if time_split[0] == '12':
      time_split[0] = '00'
    elif int(time_split[0]) < 10:
      time_split[0] = "%02d" % int(time_split[0])

  else:
    time_split = explode[4].split(':')
    if int(time_split[0]) in range(1, 12):
      time_split[0] = str(int(time_split[0]) + 12)


  if month_of_the_year.index(explode[1]) < 12:
    explode[1] = "%02d" % (month_of_the_year.index(explode[1])+1)

  return explode[3]+'-'+explode[1]+'-'+day_of_the_month+' '+time_split[0]+':'+time_split[1]+':00'

print convert_to_mysql_format("Lun Ene 27, 2014 9:52 am")
print convert_to_mysql_format("Lun Ene 27, 2014 9:52 pm")

这是两个时间的记录。第一个是2014年1月27日早上9点52分,第二个是同一天晚上9点52分。

撰写回答