2

I've been working on trying to convert a given time to a different format, taking into account an external device's timezone, skipping the OS's timezone conversions.

Initially, I have a time in UTC seconds, and the timezone from the device. For example, where I am right now the time is seconds=1343931446, and timezone = -0700. What I'm trying to do is convert this to the format YYYYMMDD_HHMMSS, which has worked properly for a while. For the above values, it should come out to be 20120802_111726.

This following block of code worked since I wrote it, conveniently on July 11th. The issue comes down to the fact that when the day is only 1 digit long (aka starting yesterday), the parsing goes wrong, and I get 20120821_011726. I'm presuming the issue is when I convert the time value into date time, as when I print time_t, I'll get time.struct_time(tm_year=2012, tm_mon=8, tm_mday=2, tm_hour=18, tm_min=17, tm_sec=26, tm_wday=3, tm_yday=215, tm_isdst=0), which is treated as single character strings when parsed into a datetime.

The question is, can I force datetime to accept a 2-character input for the day of the month/hour so it will parse properly, or is there a better way of transforming these formats? Keep in mind that this current method was written due to not being able to use any methods that account for the current system time, as this is done where the time zone is not guaranteed to be same on the system as the device that the seconds were obtained from.

def convert_time(seconds, tz):
    """ Times obtained were in seconds since epoch. 
        Convert to format YYYYMMDD_HHMMSS.
    """
    time_t = time.gmtime(seconds) # convert to time tuple
    # convert to datetime format - because time zone comparisons can't be made
    # in a format directly convertible from UTC
       time_dt = datetime.datetime.strptime(str(time_t.tm_year) + 
                                            str(time_t.tm_mon)  + 
                                            str(time_t.tm_mday) +
                                            str(time_t.tm_hour) + 
                                            str(time_t.tm_min)  + 
                                            str(time_t.tm_sec), 
                                            '%Y%m%d%H%M%S')

    # Convert time zone to timedelta
    offset = datetime.timedelta(hours=int(tz.lstrip('-')[:2]), 
                                minutes=int(tz.lstrip('-')[2:]))
    sign = -1 if tz.startswith('-') else 1
    time_dt = time_dt + sign * offset
    time_dt = time_dt.strftime('%Y%m%d_%H%M%S')

    return time_dt
4
  • 2
    Why not use datetime.datetime(*time_t[:6], tzinfo=None)?
    – Martijn Pieters
    Aug 2, 2012 at 18:32
  • Also, you can use a timezone object (see the documentation) to handle the offset; a timedelta object is not the way to go.
    – Martijn Pieters
    Aug 2, 2012 at 18:34
  • That method of converting worked perfectly. I know my method was very roundabout, and the error made it even worse. Feel free to post that as the answer.
    – r36363
    Aug 2, 2012 at 18:37
  • I've one-upped it and cut out datetime altogether.
    – Martijn Pieters
    Aug 2, 2012 at 18:41

1 Answer 1

1

Your timestamp is expressed in seconds, your timezone in hours and minutes. Simply subtract or add the timezone converted to seconds, then use the time.strftime function to format that to the string you want:

def convertTime(seconds, tz):
    tzhours, tzminutes = map(int, (tz.lstrip('-')[:2], tz[-2:]))
    offset = tzhours * 3600 + tzminutes * 60
    if tz.startswith('-'):
        offset *= -1
    return time.strftime('%Y%m%d_%H%M%S', time.gmtime(seconds + offset))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.