如何将 EST/EDT 转换为 GMT?

发布于 2024-10-27 20:39:44 字数 191 浏览 4 评论 0原文

我在一列中有一些记录,代表 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
...

有人可以帮我吗?谢谢

I have a few records inside a column which represent either EST or EDT Time. I need to convert these times to GMT time. The format of the time are:

10/1/2010   0:0:0
10/1/2010   0:6:0
...
10/1/2010   23:54:0
...
10/3/2010   0:0:0
...

Can someone help me out here? thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

泛滥成性 2024-11-03 20:39:44

我知道在时区之间转换的最简单、最可靠的方法是使用第三方 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/2002 1:30:00”将是不明确的:

>>> eastern.localize(datetime(2002, 10, 27, 1, 30, 00), is_dst=None)
AmbiguousTimeError: 2002-10-27 01:30:00

因为由于夏令时,该时间发生了两次。
还有一些日期时间,例如 2002-04-07 02: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 

上面测试的最后两个日期显示,即使时间接近 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)

The easiest, most reliable way I know to convert between timezones is to use the third-party pytz module:

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))

yields:

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

Note however, your data does not specify if the datetime is in the EST or EDT timezone.
There are some times which are ambiguous when you don't specify EST or EDT. For example, '10/27/2002 1:30:00' would be ambiguous:

>>> eastern.localize(datetime(2002, 10, 27, 1, 30, 00), is_dst=None)
AmbiguousTimeError: 2002-10-27 01:30:00

since this time happened twice due to Daylight Savings Time.
Also some datetimes, like 2002-04-07 02:30:00,
are nonexistent. See this link
for a discussion of these and even more bizarre issues that arise when dealing with localtimes.

If you are willing to overlook these knotty corner cases, and if your machine is setup in the local timezone (e.g. EST/EDT),
there is a way to convert between the local and UTC timezones which does
not require the installation of pytz. The idea is to convert the datetime --> timetuple --> timestamp --> UTC datetime. The chain of conversions is done with

dt.datetime.utcfromtimestamp(time.mktime(date.timetuple()))

For example:

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

yields

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 

The last two dates tested above show the conversion works correctly even with times close to the switch between EST and EDT.


In summary, using the alternate method (without pytz), here is how to convert datetime objects representing local time to datetime objects representing GMT
time, and vice versa:

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)
拔了角的鹿 2024-11-03 20:39:44

每条记录的伪代码:

制作一个时间戳字符串: field[0].strip() + " " + field[1].strip()

使用 datetime.datetime.strptime() 将其转换为 datetime.datetime 实例

添加一个 timedelta例如 timedelta(hours=-4) 到您的时间戳,

使用 timestamp.strftime() 生成您想要的输出的任何字符串表示形式。

对于时间字段为空的情况:如果这意味着 0:0:0,请修改以上内容以适应。如果这意味着“时间未知”,那么您需要做其他事情......

Pseudocode for each record:

make a timestamp string: field[0].strip() + " " + field[1].strip()

use datetime.datetime.strptime() to convert that into a datetime.datetime instance

add a timedelta e.g. timedelta(hours=-4) to your timestamp

use timestamp.strftime() to produce whatever string representation you want for the output.

For the case where the time field is empty: If that means 0:0:0, modify the above to suit. If it means "time unknown", you'll need to do something else ...

狠疯拽 2024-11-03 20:39:44

假设我们有一个美国/东部时间的日期时间字符串“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

Assume that we have a datetime string as "2019-04-09T23:59:55ET" in US/Eastern time.
Here is the function to convert string to 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

绻影浮沉 2024-11-03 20:39:44

如果没有关联的时间,时区就无关紧要……日期也不能转换为不同的时区。另一栏里有相关时间吗?

编辑:好吧,现在有时间了,我会让 python 大师接手。 ;]

Without an associated time, the time zone doesn't matter ... nor can the date be translated to a different time zone. Is there a related time in another column?

EDIT: Alright, now that there IS a time, I'll let the python guru's take over. ;]

夜雨飘雪 2024-11-03 20:39:44

您可以使用 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))

最后一行的作用是从日期时间对象中删除时区信息,这样您就可以只操作日期和时间(不用担心,这不会改变再次输入时区,它只是将其从时间戳字符串中删除)。

You can use pandas.DataFrame.tz_convert() like this:

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))

What the last row does is removing the timezone info from the datetime object, so you can operate with the date and time only (don't worry, that doesn't change the timezone again, it just strips it from the timestamp string).

爱要勇敢去追 2024-11-03 20:39:44

我必须在 Python 中创建一个自定义函数来将 EST 转换为 GMT,这是我编写的代码:

#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 的支持。目前是二月,正在遵循美国东部时间。如有任何更改或更正,欢迎!

I had to create a custom function in Python to convert EST to GMT, here's the code I've written:

#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)

I haven't added support for EDT. It is February currently and EST is being followed. Any changes or corrections are welcome!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文