Home > other >  Converting jalali dates to gregorian dates in python
Converting jalali dates to gregorian dates in python

Time:12-28

I want to convert a date in jalali format ۱۱ فروردین ۱۴۰۰ to gregorian format

I tried to use pd.to_datetime but it returned unknown date format

CodePudding user response:

First you should create a dictionary of persian months and convert them to their month number:

# Using the dict function
# Using curly braces
dict2 = {'فروردین': '1', 'اردیبهشت': '2', 'خرداد': '3'}
text = "۱۱ فروردین ۱۴۰۰"

# Iterate over the keys of the dictionary
for key in dict2:
    # Check if the key is in the string
    if key in text:
        # Replace the key with its value
        text = text.replace(key, dict2[key])

print(text)  

since your numbers are in farsi unicode, you should now convert the farsi numbers to english:

from unidecode import unidecode

# Convert persian numbers to english numbers

# text = "۱۱ فروردین ۱۴۰۰"
text = unidecode(text)

print(text)  

now the string should be in a proper format for jdatetime library to be used:

# text = '1 10 1400'
jalali_date_list = text.split()

# Convert the elements of the list to integers
jalali_date = (int(jalali_date_list[2]), int(jalali_date_list[1]), int(jalali_date_list[0]))

print(jalali_date)  # Output: (1400, 1, 11)

finally convert it with jdatetime:

import jdatetime

# Convert the jalali date to a tuple of (year, month, day)

# Convert the jalali date to a gregorian date
gregorian_date = jdatetime.date(*jalali_date).togregorian()

print(gregorian_date)  # Output: (2021, 3, 31)

  • Related