Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 将时区字符串(即美国/东部)转换为偏移量_Ruby_Timezone_Logstash - Fatal编程技术网

Ruby 将时区字符串(即美国/东部)转换为偏移量

Ruby 将时区字符串(即美国/东部)转换为偏移量,ruby,timezone,logstash,Ruby,Timezone,Logstash,我正在寻找纯Ruby中的一种方法,即获取一个时区字符串,例如“US/Eastern”,并将其与时间戳的字符串表示一起使用,以转换为一个带有时区的时间戳 到目前为止,我只找到了strtime,它支持像“EST”这样的短时区名称或像“-0500”这样的时区偏移量,但不支持完整的时区字符串 我需要能够作为Logstash ruby过滤器的一部分来运行它。我有一些JSON包含时间戳,没有时区,如下所示: { “事件”:{ “已创建”:“2021-02-15_11-26-29”, }, “账户”:[ {

我正在寻找纯Ruby中的一种方法,即获取一个时区字符串,例如“US/Eastern”,并将其与时间戳的字符串表示一起使用,以转换为一个带有时区的时间戳

到目前为止,我只找到了
strtime
,它支持像“EST”这样的短时区名称或像“-0500”这样的时区偏移量,但不支持完整的时区字符串

我需要能够作为Logstash ruby过滤器的一部分来运行它。我有一些JSON包含时间戳,没有时区,如下所示:

{
“事件”:{
“已创建”:“2021-02-15_11-26-29”,
},
“账户”:[
{
“名称”:“操作员”,
“标题”:“服务器\\操作员”,
“域”:“服务器”,
“PasswordChanged”:“False”,
“PasswordRequired”:“True”,
“PasswordExpires”:“False”,
“已禁用”:“错误”,
“锁定”:“假”,
“LocalAccount”:“True”,
“全名”:“操作员”,
“状态”:“确定”,
“LastLogon”:“2020年8月7日下午2:14:13”
},
...
]
}
对于event.created字段,我可以使用
date
过滤器:

    date {
        match => [ "[event][created]", "yyyy-MM-dd_HH-mm-ss" ]
        timezone => "${TIMEZONE}"
        target => "[event][created]"
    }
其中,
${TIMEZONE}
是保存完整时区名称的环境变量,即“US/Eastern”。但是对于Acounts.LastLogin字段,我不能使用
date
过滤器,因为它位于可变长度的列表中,所以我必须使用ruby过滤器。我能做的最接近的事情是:

    ruby {
        code => 'event.get("[Accounts]").each_index {|x|
                    tz = "-0500"
                    last_logon_str = event.get("[Accounts][#{x}][LastLogon]")
                    last_logon = DateTime.strptime(last_logon_str + " " + tz, "%m/%d/%Y %I:%M:%S %p %z")
                    event.set("[users][#{x}][last_logon]", last_logon.strftime("%Y-%m-%dT%H:%M:%S%z"))
                 }'
    }

当然,这是使用硬编码的时区偏移量,而不是包含全名的变量

我在查看的
Time
对象的文档中指出,可以使用
时区创建
Time
对象:

或时区对象:

tz = timezone("Europe/Athens") # Eastern European Time, UTC+2
Time.new(2002, 10, 31, 2, 2, 2, tz) #=> 2002-10-31 02:02:02 +0200
然后我可以用它来提取偏移量,但我在任何地方都找不到对
时区的引用

处理这个问题的最佳方法是什么?

时区是课程的一部分。你需要它。下面的代码

    ruby {
        code => '
            require "tzinfo"
            tz = TZInfo::Timezone.get(ENV["TIMEZONE"])
            event.set("offset", tz.observed_utc_offset())
        '
    }

当$TIMEZONE为“US/Eastern”时,获取我的
“offset”=>-18000,

事件时间需要传递到
观测到的utc\u offset
。否则,您将获得当前偏移量—它不一定是事件发生时有效的偏移量。(根据,默认值是
时间。现在
)这已经足够接近我要找的时间了。如果需要以小时:分钟为单位的偏移量,则观察到的
utc\u偏移量的输出没有帮助,但我使用了
tz.now.strftime(“%z”)
来获得“-05:00”的值,该值可以使用
%z
strtime
进行时间戳解析。