如何使用python在utc中将带时区的字符串转换为datetime? [英] How to convert string with timezone to datetime in utc with python?

查看:467
本文介绍了如何使用python在utc中将带时区的字符串转换为datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的 Python 。我被困在某一点。我有将时间存储为具有指定时区的字符串的变量。

I am new Python. I am stuck at one point. I have variable that store time as string with specified timezone.

如下所示

>>> print usertime
2017-08-18T08:00:00+04:30
>>> type(usertime)
<type 'str'>

所以我只想转换 usertime 时间到utc时间,输出应从 2017-08-18T08:00:00 中减去 4小时30分钟。输出转换如下所示: 2017-08-18T03:30:00 按照utc格式。

So I just want to convert usertime time to utc time, The output should subtract 4 hours and 30 minutes from 2017-08-18T08:00:00. The output conversion will look like: 2017-08-18T03:30:00 as per utc format.

推荐答案

您要先将字符串转换为类似对象的日期时间。您的字符串的问题在于,时区的格式无法识别 datetime

You want to convert the string to a datetime like object first. The problem with your string is that the timezone is in a format that datetime doesn't recognise.

您可以使用熊猫时间戳

import pandas as pd

ts = pd.Timestamp(string).tz_convert("UTC")
output = ts.strftime("%Y-%m-%dT%H:%M:%S")

或者,如果您不想安装/使用熊猫,可以转换字符串格式,然后使用 datetime

Alternatively, if you don't want to install/use Pandas, could convert the string format, and then use datetime.

import datetime
import pytz
import re

# Remove the ':' from the timezone, if it's there.
string = re.sub("\+(?P<hour>\d{2}):(?P<minute>\d{2})$", "+\g<hour>\g<minute>" , string)
# Create the datetime object.
dt = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
# Convert to UTC
dt = dt.astimezone(pytz.UTC)
output = dt.strftime("%Y-%m-%dT%H:%M:%S")

如果您使用的是python 2.7,并且在调用%z > strptime 的标准解决方法是:

If you're using python 2.7, and can't specify %z when calling strptime the standard workaround is to do this:

def parse(string):
    dt = datetime.strptime(string[0:19],'%Y-%m-%dT%H:%M:%S')
    if string[19] == "+":
        dt -= datetime.timedelta(hours=int(string[20:22]), 
                                 minutes=int(string[22:]))
    elif t[19]=='-':
        dt += datetime.timedelta(hours=int(string[20:22]),
                                 minutes=int(string[22:]))
    return dt

与Stefano的答案相比,上述方法的优势在于它们可以使用任意偏移量工作。不只是四个半小时。

The advantage of the methods above, vs Stefano's answer, is that they will work with an arbitrary offset. Not just for four and half hours.

这篇关于如何使用python在utc中将带时区的字符串转换为datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆