字符串转换为datetime时区

时间:2015-01-11 22:21:40

标签: python datetime

我想在两个时间字符串之间线性插值一些点。

所以我尝试将字符串转换为datetime然后插入一些点然后将datetime转换为string。但似乎时区不正确。

在下面的例子中。我想在9-28 11:07:57.435和#34;之间插入一点。和" 9-28 12:00:00.773"。

#!/usr/bin/env python
import numpy as np
from time import mktime
from datetime import datetime

#-----------------------------------------#
def main():
    dtstr = [
"9-28 11:07:57.435",
"9-28 12:00:00.773"
]
    print "input",dtstr
    dtlst = str2dt(dtstr)
    floatlst = dt2float(dtlst)

    bins = 3
    x1 = list(np.arange(floatlst[0],floatlst[-1],(floatlst[-1]-floatlst[0])/bins))
    dtlst = float2dt(x1)
    dtstr = dt2str(dtlst)
    print "output",dtstr
    return

def str2dt(strlst):
    dtlst = [datetime.strptime("2014-"+i, "%Y-%m-%d %H:%M:%S.%f") for i in strlst]
    return dtlst

def dt2float(dtlst):
    floatlst = [mktime(dt.timetuple()) for dt in dtlst]
    return floatlst

def dt2str(dtlst):
    dtstr = [dt.strftime("%Y-%m-%d %H:%M:%S %Z%z") for dt in dtlst]
    return dtstr

def float2dt(floatlst):
    dtlst = [datetime.utcfromtimestamp(seconds) for seconds in floatlst]
    return dtlst

#-----------------------------------------#
if __name__ == "__main__":
    main()

输出如下:

input ['9-28 11:07:57.435', '9-28 12:00:00.773']
output ['2014-09-28 16:07:57 ', '2014-09-28 16:25:18 ', '2014-09-28 16:42:39 ']

这里有两个问题:

  1. 输入和输出有4个小时不同(9-28 16:07:57到9-28 11:07:57)。我想这是由时区引起的,但不知道如何修复它。
  2. 我希望第一个和最后一个点与输入相同,但现在似乎最后一点小于输入的最后一点(16:42:39 vs 12:00:00)。

1 个答案:

答案 0 :(得分:0)

Q1。你的时区是正确的,你使用time.mktime converts struct_time to seconds assuming the input is local time,然后使用datetime.utcfromtimestamp(自然)转换为utc。使用datetime.fromtimestamp代替将所有内容保存在当地时间。

Q2。与原生Python range / xrange一样,当您执行numpy.arange(x, y, z)时,结果以x开头并向上移动,但不包括y except in weird floating point roundoff cases. Don'依靠这种行为)。如果您希望在具有浮动值的端点上保持一致的行为,请使用numpy.linspace

另一方面,为什么要将datetime转换为秒,然后再返回? datetime对象支持加法和减法。以下是我的建议。

from time import mktime, localtime
from datetime import datetime
from copy import copy

def main():
    input_timestrings = ["9-28 11:07:57.435", "9-28 12:00:00.773"]
    input_datetimes = timestrings_to_datestimes(input_timestrings)

    start_datetime = input_datetimes[0]
    end_datetime = input_datetimes[1]

    # subtraction between datetime objects returns a timedelta object
    period_length = end_datetime - start_datetime

    bins = 3

    # operation w/ timedelta objects and datetime objects work pretty much as you'd expect it to
    delta = period_length / bins
    datetimes = list(custom_range(start_datetime, end_datetime + delta, delta))
    output_timestrings = datetimes_to_timestrings(datetimes)

    print output_timestrings
    return

def timestrings_to_datetimes(timestrings):
    datetimes = [datetime.strptime("2014-"+timestring, "%Y-%m-%d %H:%M:%S.%f") for timestring in timestrings]
    return datetimes

def datetimes_to_timestrings(datetimes):
    timestrings = [datetime_.strftime("%Y-%m-%d %H:%M:%S %Z%z") for datetime_ in datetimes]
    return timestrings

def custom_range(start, end, jump):
    x = start
    while x < end:
        yield x
        x = x + jump


if __name__ == "__main__":
    main()