Is it possible with Python to set the timezone just like this in PHP:
date_default_timezone_set("Europe/London");
$Year = date('y');
$Month = date('m');
$Day = date('d');
$Hour = date('H');
$Minute = date('i');
I can’t really install any other modules etc as I’m using shared web hosting.
Any ideas?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'
To get the specific values you’ve listed:
>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')
See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.
Method 2
Be aware that running
import os
os.system("tzutil /s "Central Standard Time"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London' >>> time.tzset()
which will only set in the current environment time (in Unix only)
Method 3
For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s “Central America Standard Time”
For further reference:
http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
Method 4
You can use pytz as well..
import datetime
import pytz
def utcnow():
return datetime.datetime.now(tz=pytz.utc)
utcnow()
datetime.datetime(2020, 8, 15, 14, 45, 19, 182703, tzinfo=<UTC>)
utcnow().isoformat()
'
2020-08-15T14:45:21.982600+00:00′
Method 5
It’s not an answer, but…
To get datetime components individually, better use datetime.timetuple:
time = datetime.now() time.timetuple() #-> time.struct_time( # tm_year=2014, tm_mon=9, tm_mday=7, # tm_hour=2, tm_min=38, tm_sec=5, # tm_wday=6, tm_yday=250, tm_isdst=-1 #)
It’s now easy to get the parts:
ts = time.timetuple() ts.tm_year ts.tm_mon ts.tm_mday ts.tm_hour ts.tm_min ts.tm_sec
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0