1

The following code snippet print the day for example. Monday (or) Tuesday etc.. But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.

import datetime
from datetime import date
current_day_name =  (date.today().strftime("%A")).lower()
print(current_day_name)

Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?

Mahesh
  • 1,117
  • 2
  • 23
  • 42

1 Answers1

0

Here is a quote from the datetime library reference:

Because the format depends on the current locale, care should be taken when making assumptions about the output value.

So datetime depends on the locale settings. The locale reference describes a function setlocale:

Applications typically start with a call of:

import locale
locale.setlocale(locale.LC_ALL, '')

So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.

As an example, on my computer I run

>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'

It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference). For example:

>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
    datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'
Nathan Chappell
  • 2,099
  • 18
  • 21
  • 1
    Hi. Locale controls only formatting and is not relevant to time zone. Also, you are passing a fixed offset, not an actual time zone. (Fixed offsets do not handle daylight saving time or changes in standard time.) The correct approach would need to involve pytz, arrow, or dateutil in order to use an actual time zone. – Matt Johnson-Pint Feb 15 '20 at 17:35