donde321
Posts: 11
Joined: Mon Apr 11, 2016 10:54 pm

Local time to UTC

Thu Apr 14, 2016 2:01 pm

I want to switch from local time to UTC using strftime. The code shown below works for 12 hour local time and 24 hour local time. I want to replace the 24 hour local with GMT. The Python reference for time and date using strftime shows %z to do this conversion. But, it doesn't seem to work. Ten's of blogs show all kinds of ways to do this. I would like to use strftime if I could. The else line is the 24 hour local time statement I want to replace.

Code: Select all

def display_time():
	# Collect current time and date
	if(time_format):
		current_time = time.strftime("%I:%M")
	else:
		current_time = time.strftime("%H:%M")   

User avatar
DougieLawson
Posts: 39296
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Local time to UTC

Fri Apr 15, 2016 1:07 pm

Try this

Code: Select all

from time import gmtime, localtime, strftime
utc = strftime("%a, %d %b %Y %H:%M:%S %Z", gmtime())
local = strftime("%a, %d %b %Y %H:%M:%S %Z", localtime())
print local, utc
I couldn't get %z # lower case zed to work.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

donde321
Posts: 11
Joined: Mon Apr 11, 2016 10:54 pm

Re: Local time to UTC

Fri Apr 15, 2016 2:56 pm

Hey Dougie, You sure helped me today. All other methods didn't seem to work.
Thanks so much. I only needed the hours and minutes, in local and gmt. So removed the others. Good Day!

Return to “Python”