def row_to_datapoint(row: str) -> dict:
    """
        Format data based on mCerebrum's current GZ-CSV format into what Cerebral
    Cortex expects
    :param row:
    :return:
    """
    ts, offset, values = row.split(',', 2)
    ts = int(ts) / 1000.0
    offset = int(offset)

    if isinstance(values, tuple):
        values = list(values)
    else:
        try:
            values = json.loads(values)
        except:
            try:
                values = [float(values)]
            except:
                try:
                    values = list(map(float, values.split(',')))
                except:
                    values = values

    timezone = datetime.timezone(datetime.timedelta(milliseconds=offset))
    ts = datetime.datetime.fromtimestamp(ts, timezone)
    return DataPoint(start_time=ts, sample=values)
Пример #2
0
def convertutctimetolocaltime(twittercreatedate):
    localtimezone = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo
    twittercreatedatestrptime = datetime.datetime.strptime(twittercreatedate, "%a %b %d %H:%M:%S %z %Y")
    convertutctolocal = twittercreatedatestrptime.replace(tzinfo=pytz.utc).astimezone(localtimezone)
    datelocal = datetime.datetime.strftime(convertutctolocal, "%m/%d/%Y")
    timelocal = datetime.datetime.strftime(convertutctolocal, "%I:%M:%S %p")
    return datelocal, timelocal
    def regresion(self, sensor):
        df_filtrado = self.df[self.df["sensor"] == sensor]
        df_filtrado = df_filtrado.tail(self.ventana)
        df_filtrado['fecha'] = pd.to_datetime(df_filtrado.pop('fecha'),
                                              format='%d.%m.%Y %H:%M:%S')
        df_filtrado['segundos'] = [
            time.mktime(t.timetuple()) - 18000 for t in df_filtrado['fecha']
        ]
        tiempo = df_filtrado['segundos'].std(skipna=True)
        if np.isnan(tiempo):
            return
        tiempo = int(round(tiempo))
        ultimo_tiempo = df_filtrado['segundos'].iloc[-1]
        ultimo_tiempo = ultimo_tiempo.astype(int)
        range(ultimo_tiempo + tiempo,
              (self.pronostico + 1) * tiempo + ultimo_tiempo, tiempo)
        nuevos_tiempos = np.array(
            range(ultimo_tiempo + tiempo,
                  (self.pronostico + 1) * tiempo + ultimo_tiempo, tiempo))

        X = df_filtrado["segundos"].to_numpy().reshape(-1, 1)
        Y = df_filtrado["valor"].to_numpy().reshape(-1, 1)
        linear_regressor = LinearRegression()
        linear_regressor.fit(X, Y)
        Y_pred = linear_regressor.predict(nuevos_tiempos.reshape(-1, 1))
        for tiempo, prediccion in zip(nuevos_tiempos, Y_pred):
            time_format = datetime.utcfromtimestamp(tiempo)
            date_time = time_format.replace(
                tzinfo=datetime.timezone(datetime.timedelta(
                    hours=-5))).isoformat()
            self.publicar(
                "prediccion-{}".format(sensor),
                "{topic:{},payload:{},timestamp:{}}".format(
                    sensor, prediccion[0], date_time))
Пример #4
0
    def dict_to_object(self, d):
        if '__type__' not in d:
            return d

        type = d.pop('__type__')
        try:
            dateobj = datetime(**d)
            # TODO verify working!
            tzone = datetime.timezone(d['tzinfo'])
            loc_dt = tzone.localize(dateobj)
            return loc_dt
        except:
            d['__type__'] = type
            return d
Пример #5
0
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)

8. 本地时间转换为UTC时间
一个datetime类型有一个时区属性tzinfo,但是默认为None。
所以无法区分这个datetime到底是哪个时区,除非通过该属性强行给datetime设置一个时区:

>>> from datetime import datetime, timedelta, timezone
>>> tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
>>> dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00
>>> dt
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))

9. 通过astimezone实现时区的转换
# 拿到UTC时间,并强制设置时区为UTC+0:00:
>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> print(utc_dt)
2016-06-17 16:13:12.377316+00:00
# astimezone()将转换时区为北京时间:
>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
>>> print(bj_dt)
2016-06-17 16:13:12.377316+08:00

例子:
假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:

import re
Пример #6
0
 def tz():
     return datetime.timezone(datetime.timedelta(seconds=tms.tm_gmtoff))
Пример #7
0
	datetime.datetime(2018, 5, 19, 20, 25, 16, 282094)
	>>> now - timedelta(days=2, hours=6)
	datetime.datetime(2018, 5, 7, 14, 25, 16, 282094)

本地时间转为UTC时间
	本地时间是指系统设定时区的时间,例如北京时间是UTC+8:00时区的时间,而UTC时间指UTC+0:00时区的时间。
		一个datetime类型有一个时区属性tzinfo,但是默认为None,
	所以无法区分这个datetime到底是哪个时区,除非强行给datetime设置一个时区:
	>>> from datetime import datetime, timedelta, timezone
	>>> utc_8 = timezone(timedelta(hours=8))	## 创建时区UTC+8:00
	>>> now = datetime.now()
	>>> now
	datetime.datetime(2018, 5, 9, 20, 30, 3, 467520)	
	>>> dt = now.replace(tzinfo=utc_8)	#强制设置为UTC+8:00
	>>> dt
	datetime.datetime(2018, 5, 9, 20, 30, 3, 467520, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))	
	#如果系统时区恰好是UTC+8:00,那么上述代码就是正确的,否则,不能强制设置为UTC+8:00时区。

时区转换
	通过utcnow()拿到当前的UTC时间,再转换为任意时区的时间:
	# 拿到UTC时间,并强制设置时区为UTC+0:00:
	>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)	
	>>> print(utc_dt)
	2018-05-09 12:33:57.221890+00:00

	# astimezone()将转换时区为北京时间:
	>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
	>>> print(bj_dt)
	2018-05-09 20:33:57.221890+08:00

	# astimezone()将转换时区为东京时间:
Пример #8
0
from datetime import datetime, timedelta, timezone
tz_utc_8 = timezone(timedelta(hours=8))  # 创建时区UTC+8:00
now = datetime.now()
print(now)
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
dt = now.replace(tzinfo=tz_utc_8)  # 强制设置为UTC+8:00
print(dt)
datetime.datetime(2015,
                  5,
                  18,
                  17,
                  2,
                  10,
                  871012,
                  tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))
# 如果系统时区恰好是UTC+8:00,那么上述代码就是正确的,否则,不能强制设置为UTC+8:00时区。

# 时区转换
#
# 我们可以先通过utcnow()拿到当前的UTC时间,再转换为任意时区的时间:
# 拿到UTC时间,并强制设置时区为UTC+0:00:
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
# 2015-05-18 09:05:12.377316+00:00

# astimezone()将转换时区为北京时间:
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(bj_dt)
# 2015-05-18 17:05:12.377316+08:00
Пример #9
0
async def _zikannnnnnn(ctx):
    # t = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    now = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9)))
    color = random.randint(0x000000, 0xffffff)
    await ctx.send(embed=discord.Embed(title="時間です。よく見ておいてくださいね。", description=f"{now}", color=color))
Пример #10
0
<class 'datetime.timedelta'>
>>> diff.days
2109
>>> diff.total_seconds()
182223650.0
>>> today + timedelta(days=49)
datetime.date(2021, 5, 16)
>>> now + timedelta(weeks=7)
datetime.datetime(2021, 5, 16, 15, 25, 16, 258274)


# parsing (stdlib)
>>> datetime.fromisoformat('1977-11-24T19:30:13+01:00')
datetime.datetime(
    1977, 11, 24, 19, 30, 13,
    tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))
)

>>> datetime.fromtimestamp(time.time())
datetime.datetime(2021, 3, 28, 15, 42, 2, 142696)

>>> datetime.now()
datetime.datetime(2021, 3, 28, 15, 42, 1, 120094)


# arrow small demo
>>> import arrow
>>> arrow.utcnow()
<Arrow [2021-03-28T14:43:20.017213+00:00]>
>>> arrow.now()
<Arrow [2021-03-28T15:43:39.370099+01:00]>