[英]how to convert time and time zone into date in python?
One column of CSV file includes time and time zone.一列 CSV 文件包括时间和时区。 Here is one value under the column:
2018-05-20 15:05:51.065 America/New_York
.这是列下的一个值:
2018-05-20 15:05:51.065 America/New_York
。 I wonder, how can I convert the value to the 2019-05-20
format?我想知道,如何将值转换为
2019-05-20
格式? There are over a half-million rows in the CSV file. CSV 文件中有超过 50 万行。
Split your column into date, time and zone using string manipulators, regex etc .使用字符串操作符、正则表达式等将您的列拆分为日期、时间和区域。 Have a standard time zone to follow (eg: UTC)
有一个标准时区要遵循(例如:UTC)
Now现在
How to convert string timezones in form (Country/city) into datetime.tzinfo 如何将形式(国家/城市)的字符串时区转换为 datetime.tzinfo
If you just want it to be a string, just strip away everything past the first space: "2018-05-20 15:05:51.065 America/New_York".split(' ')[0]
如果你只是想让它成为一个字符串,只需
"2018-05-20 15:05:51.065 America/New_York".split(' ')[0]
第一个空格之后的所有内容: "2018-05-20 15:05:51.065 America/New_York".split(' ')[0]
EDIT: If you want it to be a timezone-aware datetime object, you can do it easily with pytz package:编辑:如果您希望它成为时区感知日期时间对象,您可以使用 pytz 包轻松完成:
from datetime import datetime
from pytz import timezone
string_date = "2018-05-20 15:05:51.065 America/New_York"
tz = timezone(string_date.split(' ')[len(string_date.split(' '))-1])
unaware = " ".join(string_date.split(' ')[:len(string_date.split(' '))-1])
unaware_datetime = datetime.strptime(unaware, "%Y-%m-%d %H:%M:%S.%f")
aware_datetime = unaware_datetime.replace(tzinfo=tz)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.