Python 偏移转换为非偏移的日期
Python date with offset conversion to non-offset
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from dateutil.tz import gettz
from datetime import datetime, timedelta
input_time = '2019-02-01 09:50:08+11:00'
parsed=parse(input_time)
print parsed.tzinfo
我有时间输入字符串:
input_time = '2019-02-01 09:50:08+11:00'
我想将其转换成这种格式:YYYY-MM-DD HH:MM:SS。基本上,将偏移量添加到实际时间对象。对于上面的示例,我正在寻找以下输出:
input_time_converted = '2019-02-01 20:50:08'
在 dateutil 库中找到一些有用的东西来解析作为字符串传递的日期对象并获取偏移量详细信息,但它给了我这个输出:
tzoffset(None, 39600)
但我不知道如何从上面得到实际数字并进行其余的数学运算。
我试过调用它 - 正如官方 dateutil 解析器文档中所解释的 -
print parsed.tzinfo.tzoffset
但是没用。
#!/usr/bin/env python2
def process_messed_up_timestamp(ts):
"""Convert messed up timestamps to something else.
Input timestamp is in UTC format with the offset that
should be applied but hasn't been.
"""
from datetime import datetime, timedelta
timestamp, plus, offset = ts[:19], ts[19], ts[20:]
# should validate plus is '+' or '-'
fmt = '%Y-%m-%d %H:%M:%S'
base = datetime.strptime(timestamp, fmt)
hours, minutes = [int(n) for n in offset.split(':')]
delta = timedelta(hours=hours, minutes=minutes)
multiplier = -1 if plus == '-' else 1
return (base + multiplier * delta).strftime(fmt)
input_time = '2019-02-01 09:50:08+11:00'
input_time_converted = '2019-02-01 20:50:08'
assert process_messed_up_timestamp(input_time) == input_time_converted
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from dateutil.tz import gettz
from datetime import datetime, timedelta
input_time = '2019-02-01 09:50:08+11:00'
parsed=parse(input_time)
print parsed.tzinfo
我有时间输入字符串:
input_time = '2019-02-01 09:50:08+11:00'
我想将其转换成这种格式:YYYY-MM-DD HH:MM:SS。基本上,将偏移量添加到实际时间对象。对于上面的示例,我正在寻找以下输出:
input_time_converted = '2019-02-01 20:50:08'
在 dateutil 库中找到一些有用的东西来解析作为字符串传递的日期对象并获取偏移量详细信息,但它给了我这个输出:
tzoffset(None, 39600)
但我不知道如何从上面得到实际数字并进行其余的数学运算。
我试过调用它 - 正如官方 dateutil 解析器文档中所解释的 -
print parsed.tzinfo.tzoffset
但是没用。
#!/usr/bin/env python2
def process_messed_up_timestamp(ts):
"""Convert messed up timestamps to something else.
Input timestamp is in UTC format with the offset that
should be applied but hasn't been.
"""
from datetime import datetime, timedelta
timestamp, plus, offset = ts[:19], ts[19], ts[20:]
# should validate plus is '+' or '-'
fmt = '%Y-%m-%d %H:%M:%S'
base = datetime.strptime(timestamp, fmt)
hours, minutes = [int(n) for n in offset.split(':')]
delta = timedelta(hours=hours, minutes=minutes)
multiplier = -1 if plus == '-' else 1
return (base + multiplier * delta).strftime(fmt)
input_time = '2019-02-01 09:50:08+11:00'
input_time_converted = '2019-02-01 20:50:08'
assert process_messed_up_timestamp(input_time) == input_time_converted