Python Date Conversion. How to convert arabic date string into date or datetime object python

帅比萌擦擦* 提交于 2020-01-11 11:43:08

问题


I have to convert this date into normal date string/object.

١٩٩٤-٠٤-١١ to 11-04-1994.


回答1:


I have made a solution to this problem. May be not a best but its working :)

# -*- coding: utf8 -*-
import unicodedata
s = u"١٩٩٤-٠٤-١١"

def date_conv(unicode_arabic_date):
    new_date = ''
    for d in unicode_arabic_date:
        if d != '-':
            new_date+=str(unicodedata.decimal(d))
        else:
            new_date+='-'
    return new_date

print date_conv(s)

1994-04-11




回答2:


Here is a method I wrote to solve it:

def arab_to_decimal(timestamp):
    if not isinstance(timestamp, unicode) return
    table = {1632: 48,  # 0
             1633: 49,  # 1
             1634: 50,  # 2
             1635: 51,  # 3
             1636: 52,  # 4
             1637: 53,  # 5
             1638: 54,  # 6
             1639: 55,  # 7
             1640: 56,  # 8
             1641: 57}  # 9
    return timestamp.translate(table)

arab_to_decimal(u"١٩٩٤-٠٤-١١")



回答3:


var arabicDate = "١٩٩٤-٠٤-١١";
var europeanDate = arabicDate.replace(/[\u0660-\u0669]/g, function(m) {
  return String.fromCharCode(m.charCodeAt(m) - 0x660 + 0x30);
}).split('-').reverse().join('-');
console.log(europeanDate);
// => 11-04-1994

EDIT: Derp. Python, not JavaScript. I'll leave it here for someone to rewrite.




回答4:


To create a date object from the arabic date string:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date

d = date(*map(int, u"١٩٩٤-٠٤-١١".split('-')))
# -> datetime.date(1994, 4, 11)



回答5:


It's definitely a Good Idea to use unicodedata.decimal. There's probably a nice way to do this using the locale module and time.strptime / time.strftime, but I don't have any Arabic locales on this machine, so I'm not about to experiment. :)

FWIW, here's a fairly direct translation of Amadan's JavaScript code into a Python function.

import re

pat = re.compile(u'[\u0660-\u0669]', re.UNICODE)

def arabic_to_euro_digits(m):
    return unichr(ord(m.group(0)) - 0x630)

def arabic_to_euro_date(arabic_date):
    s = pat.sub(arabic_to_euro_digits, arabic_date)
    return '-'.join(s.split('-')[::-1])

arabic_date = u'١٩٩٤-٠٤-١١'
print arabic_date

euro_date = arabic_to_euro_date(arabic_date)
print euro_date

output

١٩٩٤-٠٤-١١
11-04-1994


来源:https://stackoverflow.com/questions/32859847/python-date-conversion-how-to-convert-arabic-date-string-into-date-or-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!