ESTまたはEDT時間を表す列内にいくつかのレコードがあります。これらの時刻をGMT時刻に変換する必要があります。時間の形式は次のとおりです。
10/1/2010 0:0:0
10/1/2010 0:6:0
...
10/1/2010 23:54:0
...
10/3/2010 0:0:0
...
誰かがここで私を助けてくれますか?ありがとう
タイムゾーン間で変換するために私が知っている最も簡単で信頼性の高い方法は、サードパーティのpytzモジュールを使用することです。
import pytz
import datetime as dt
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%d %H:%M:%S %Z%z'
text='''\
10/1/2010 0:0:0
10/1/2010 0:6:0
10/1/2010 23:54:0
10/3/2010 0:0:0
'''
for datestring in text.splitlines():
date=dt.datetime.strptime(datestring,"%m/%d/%Y %H:%M:%S")
date_eastern=eastern.localize(date,is_dst=None)
date_utc=date_eastern.astimezone(utc)
print(date_utc.strftime(fmt))
収量:
2010-10-01 04:00:00 UTC+0000
2010-10-01 04:06:00 UTC+0000
2010-10-02 03:54:00 UTC+0000
2010-10-03 04:00:00 UTC+0000
ただし、データでは、日時がESTまたはEDTタイムゾーンのどちらであるかは指定されていないことに注意してください。ESTまたはEDTを指定しないと、あいまいになる場合があります。たとえば、「10/27/20021:30:00」はあいまいになります。
>>> eastern.localize(datetime(2002, 10, 27, 1, 30, 00), is_dst=None)
AmbiguousTimeError: 2002-10-27 01:30:00
この時間は夏時間のために2回発生したためです。また、2002-04-0702:30:00などの一部の日時は存在しません。 現地時間を扱うときに発生するこれらの問題やさらに奇妙な問題の説明については、このリンクを参照してください。
これらの節のあるコーナーケースを見落としても構わないと思っていて、マシンがローカルタイムゾーン(EST / EDTなど)でセットアップされている場合は、のインストールを必要としないローカルタイムゾーンとUTCタイムゾーンの間で変換する方法がありますpytz
。アイデアは、日時->タイムスタンプ->タイムスタンプ->UTC日時を変換することです。変換のチェーンはで行われます
dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
例えば:
import time
import datetime as dt
import pytz
utc=pytz.utc
eastern=pytz.timezone('US/Eastern')
fmt='%Y-%m-%d %H:%M:%S %Z%z'
text='''\
10/1/2010 0:0:0
10/1/2010 0:6:0
10/1/2010 23:54:0
10/3/2010 0:0:0
3/13/2011 1:55:0
3/13/2011 3:00:0
'''
for datestring in text.splitlines():
date=dt.datetime.strptime(datestring,"%m/%d/%Y %H:%M:%S")
date_est=eastern.localize(date,is_dst=None)
date_utc=date_est.astimezone(utc)
date_utc2=dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
print('{d} --> {d_utc} {d_utc2}'.format(
d=date.strftime(fmt),
d_utc=date_utc.strftime(fmt),
d_utc2=date_utc2.strftime(fmt),
))
assert date_utc.hour == date_utc2.hour
収量
2010-10-01 00:00:00 EDT-0400 --> 2010-10-01 04:00:00 UTC+0000 2010-10-01 04:00:00
2010-10-01 00:06:00 EDT-0400 --> 2010-10-01 04:06:00 UTC+0000 2010-10-01 04:06:00
2010-10-01 23:54:00 EDT-0400 --> 2010-10-02 03:54:00 UTC+0000 2010-10-02 03:54:00
2010-10-03 00:00:00 EDT-0400 --> 2010-10-03 04:00:00 UTC+0000 2010-10-03 04:00:00
2011-03-13 01:55:00 EST-0500 --> 2011-03-13 06:55:00 UTC+0000 2011-03-13 06:55:00
2011-03-13 03:00:00 EDT-0400 --> 2011-03-13 07:00:00 UTC+0000 2011-03-13 07:00:00
上記でテストされた最後の2つの日付は、ESTとEDTの間の切り替えに近い時間でも変換が正しく機能することを示しています。
要約すると、代替方法(pytzなし)を使用して、現地時間を表す日時オブジェクトをGMT時刻を表す日時オブジェクトに、またはその逆に変換する方法を次に示します。
In [83]: import datetime as dt
In [84]: import time
In [85]: import calendar
In [86]: date=dt.datetime(2010,12,1,0,0,0)
In [87]: date
Out[87]: datetime.datetime(2010, 12, 1, 0, 0)
In [88]: date_utc=dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))
In [89]: date_utc
Out[89]: datetime.datetime(2010, 12, 1, 5, 0)
In [90]: date_local=dt.datetime.fromtimestamp(calendar.timegm(date_utc.timetuple()))
In [91]: date_local
Out[91]: datetime.datetime(2010, 12, 1, 0, 0)
各レコードの擬似コード:
タイムスタンプ文字列を作成します:field [0] .strip()+ "" + field [1] .strip()
datetime.datetime.strptime()を使用して、それをdatetime.datetimeインスタンスに変換します
タイムスタンプにtimedelta(hours = -4)などのtimedeltaを追加します
timestamp.strftime()を使用して、出力に必要な文字列表現を生成します。
時間フィールドが空の場合:それが0:0:0を意味する場合は、上記を適切に変更します。それが「時間不明」を意味する場合は、何か他のことをする必要があります...
米国/東部時間の日時文字列が「2019-04-09T23:59:55ET」であると想定します。文字列をUTCに変換する関数は次のとおりです。
from datetime import datetime
import pytz
eastern = pytz.timezone('US/Eastern')
def convent_est_to_utc(datetime_str):
dt = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%SET')
return dt.replace(tzinfo=eastern).astimezone(pytz.utc)
# testing
convent_est_to_utc("2019-04-09T23:59:55ET")
# The result: 2019-04-10 04:55:55+00:00
関連付けられた時刻がない場合、タイムゾーンは重要ではありません...また、日付を別のタイムゾーンに変換することもできません。別のコラムに関連する時間はありますか?
編集:さて、時間があるので、Pythonの第一人者に引き継がせます。;]
ESTをGMTに変換するためにPythonでカスタム関数を作成する必要がありました。これが、私が作成したコードです。
#convert est time to gmt. Make sure you assign the current EST values
#to the following variables
est_year
est_month
est_day
est_hour
est_min
gmt_year = est_year
gmt_month = est_month
gmt_day = est_day
gmt_hour = est_hour + 5 #gmt is ahead by 5 hrs
gmt_min = est_min
if gmt_hour > 23:
gmt_hour = gmt_hour - 23
gmt_day = est_day + 1
days_in_month = calendar.monthrange(est_year,est_month)[1] #in case the no days becomes 32..
if gmt_day > days_in_month:
gmt_day = 1
gmt_month = gmt_month + 1
if gmt_month > 12:
gmt_month = 1
gmt_year = gmt_year + 1
gmttime = datetime.datetime(gmt_year, gmt_month, gmt_day, gmt_hour, gmt_min, 0)
EDTのサポートを追加していません。現在は2月で、ESTがフォローされています。変更や修正は大歓迎です!
pandas.DataFrame.tz_convert()
次のように使用できます。
import pandas as pd
from datetime import datetime
df = pd.read_csv("your_data_file_path.csv", index_col=False, engine='python')
df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df['Date'].dt.tz_localize('US/Eastern').dt.tz_convert('UTC')
df['Date'] = df['Date'].apply(lambda x: datetime.replace(x, tzinfo=None))
最後の行は、日時オブジェクトからタイムゾーン情報を削除しているため、日付と時刻のみで操作できます(タイムゾーンが再度変更されることはなく、タイムスタンプ文字列から削除されるだけです)。