【问题标题】:convert python string date to mysql datetime将python字符串日期转换为mysql日期时间
【发布时间】:2014-04-21 12:34:30
【问题描述】:

我有一个字符串字段,女巫是从互联网上抓取的日期,内容如下:

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

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

我需要在 mysql 表中的日期时间字段中输入它们。

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

我想这是一个非常常见的问题,我想知道是否有人已经有脚本可以执行此操作,或者可以指出我可以在哪里寻找...

提前致谢!

【问题讨论】:

  • 查看datetime 在 Python 中处理日期/时间数据。
  • 第一个字符串的日期格式是什么?第二个似乎有两个月,第一个似乎包含非英语单词。
  • @fr1tz 第二个没有两个月,也是西班牙语。 Lun 是 "Lunes" = "Monday",Mar 是 "Martes" = "Tuesday"。月份似乎太“Enero”=“January”和“Febrero”=“February”。
  • @Cyber​​ 考虑到 Mar 是 March 的常见英文缩写,即 Feb 之后的月份,这尤其令人困惑!

标签: python mysql datetime internationalization locale


【解决方案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-01-27 09:52:00
2014-01-27 21:52:00

【讨论】:

  • 谢谢大神!我将 las if 调整为
  • @user2950162 首先感谢您纠正最后一个 if 语句,没有足够的调试:-)。其次“%02d”(d)=整数,(02)=如果数字表示为1位,则加前导零。考虑到像 -2 这样的负个位数不会显示为 -02,要获得 -02 结果,您必须说“%03”。
【解决方案2】:

默认情况下,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 的行为是相同的。

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

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 2016-01-28
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多