将python字符串日期转换为mysql datetim

2024-10-04 03:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串字段witch是从互联网上抓到的日期,读起来像这样:

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

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

我需要在mysql表的datetime字段中输入它们。在

^{pr2}$

我想这是一个很常见的问题,我想知道是否有人已经有一个脚本来做这件事,或者可以指出我可以在哪里寻找。。。在

提前谢谢!在


Tags: 字符串脚本datetimemysql互联网ammarfeb
2条回答
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-01-27 09:52:00
2014-01-27 21:52:00

默认情况下,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'

更改区域设置对我的系统有部分帮助:

^{pr2}$

由于某种原因,我的系统上没有为es_ES.UTF-8设置T_FMT_AMPM。要修复它,如果时间字符串以'pm'结尾,可以手动添加12小时。在

strftime()和{}行为是相同的。在

注意:其他系统上的区域设置名称可能不同。在

相关问题 更多 >