Tag Archives: python

Convert UTC time to local in Python

UTC to local:

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

UTC to local:

>>> import datetime, pytz
>>> local_tz = pytz.timezone('Asia/Tokyo')
>>> datetime.datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)
datetime.datetime(2011, 3, 4, 16, 2, 3, 311670, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)

local to UTC:

>>> import datetime, pytz
>>> datetime.datetime.now()
datetime.datetime(2011, 3, 4, 15, 6, 6, 446583)
>>> datetime.datetime.now(pytz.utc)
datetime.datetime(2011, 3, 4, 7, 6, 22, 198472, tzinfo=<UTC>)

References
https://k4ml.wordpress.com/2011/03/04/convert-utc-time-to-local/
https://stackoverflow.com/questions/4563272/convert-a-python-utc-datetime-to-a-local-datetime-using-only-python-standard-lib

Persian Text in Matplolib

from bidi.algorithm import get_display
import arabic_reshaper
def make_farsi_text(x):
reshaped_text = arabic_reshaper.reshape(x)
farsi_text = get_display(reshaped_text)
return farsi_text
xlabel = "یک محور همینجوری"
ylabel = "یک محور دیگه همینجوری"
title = "یک نمودار همینجوری"
 
 
plt.scatter(X[:,0],X[:,1],c = y, cmap = 'spring')
plt.xlabel(make_farsi_text(xlabel),fontsize = 15)
plt.ylabel(make_farsi_text(ylabel),fontsize = 15)
plt.title(make_farsi_text(title) , fontsize = 20)
plt.show()
font_title = {'family': 'B Farnaz',
'color':  'red',
'weight': 'normal',
'size': 30,
}
font_labels = {'family': 'B Nazanin',
'color':  'black',
'weight': 'normal',
'size': 20,
}
 
plt.scatter(X[:,0],X[:,1],c = y, cmap = 'spring')
plt.xlabel(make_farsi_text(xlabel),fontdict = font_labels)
plt.ylabel(make_farsi_text(ylabel),fontdict = font_labels)
plt.title(make_farsi_text(title) ,fontdict = font_title)
plt.show()

References
http://imuhammad.ir/2017/09/23/farsi-plots-python/
https://pypi.org/project/python-bidi/
https://github.com/mpcabd/python-arabic-reshaper