[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 966
  • Last Modified:

date time conversion in python

How can I convert a date time in one timezone to a date time in another timezone?

example:
I want to be able to convert:
2004 -11-25  23:45:12 GMT +8
to the exact time in GMT +1.
0
hegga
Asked:
hegga
  • 2
1 Solution
 
heggaAuthor Commented:
I'm raising the points to 500, I need this code really fast.
0
 
rjkimbleCommented:
Try this:

def convert_time( intime, newoffset ):
    # import the time module:
    import time
    # set the format:
    fmt = '%Y -%m-%d  %H:%M:%S'
    # split the input time into a time string and a time zone:
    intimestring, zone = [ x.strip( ) for x in intime.split( 'GMT' ) ]
    # parse intimestring and convert to a list:
    t = list( time.strptime( intimestring, fmt ) )
    # convert the time zone into an integer
    z = int( zone )
    # convert newoffset into an integer
    n = int( newoffset )
    # convert the hour of the list to the new hour:
    t[ 3 ] += n - z
    # return the new time as a string:
    return '%s GMT %+d' % ( time.strftime( fmt, time.localtime( time.mktime( t ) ) ), n )

Examples of usage:

>>> convert_time( '2004 -11-25  01:45:12 GMT +8', '-5' )
'2004 -11-24  12:45:12 GMT -5'
>>> convert_time( '2004 -11-25  23:45:12 GMT +8', '+1' )
'2004 -11-25  16:45:12 GMT +1'
>>> convert_time( '2004 -11-25  01:45:12 GMT +8', -5 )
'2004 -11-24  12:45:12 GMT -5'
>>> convert_time( '2004 -11-25  01:45:12 GMT +8', +1 )
'2004 -11-24  18:45:12 GMT +1'

Is that what you want?
0
 
heggaAuthor Commented:
Thnx!
It was exactly what i was looking for!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now