How to convert Gregorian date to Persian date and vice versa in Python ?
Gregorian date
Persian date
Python
All I found was some widgets and materials that would create the Persian calendar. I do not want a Persian calendar. I just want to convert dates to each other. So how can I do this?
After you searched more and more on the Internet, I found a library that someone wrote for this purpose: Jalali.py .
You can use this Python code to convert Gregorian and Persian dates to each other.
>>> import jalali >>> jalali.Persian('1393-1-11').gregorian_string() '2014-3-31' >>> jalali.Persian(1393, 1, 11).gregorian_datetime() datetime.date(2014, 3, 31) >>> jalali.Persian('1393/1/11').gregorian_string("{}/{}/{}") '2014/3/31' >>> jalali.Persian((1393, 1, 11)).gregorian_tuple() (2014, 3, 31) >>> jalali.Gregorian('2014-3-31').persian_string() '1393-1-11' >>> jalali.Gregorian('2014,03,31').persian_tuple() (1393, 1, 11) >>> jalali.Gregorian(2014, 3, 31).persian_string("{0}") '1393'
Alternatively, you can use the jdatetime library as follows:
jdatetime
import jdatetime jalili_date = jdatetime.date(1396,2,30).togregorian() gregorian_date = jdatetime.date.fromgregorian(day=19,month=5,year=2017)
See other features in the document for details.
You can use the PersianTools library:
Example:
>>> from persiantools.jdatetime import JalaliDate >>> import datetime >>> JalaliDate.today() JalaliDate(1395, 4, 18, Jomeh) >>> JalaliDate(datetime.date(1990, 9, 23)) # Gregorian to Jalali JalaliDate(1369, 7, 1, Yekshanbeh) >>> JalaliDate.to_jalali(2013, 9, 16) # Gregorian to Jalali JalaliDate(1392, 6, 25, Doshanbeh) >>> JalaliDate(1392, 6, 25).to_gregorian() # Jalali to Gregorian datetime.date(2013, 9, 16) >>> JalaliDate.fromtimestamp(578707200) # Timestamp to Jalali JalaliDate(1367, 2, 14, Chaharshanbeh)