- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设以下 pandas.DataFrame
In [108]: import pandas
In [109]: import numpy as np
In [110]: import sqlalchemy as sql
In [111]: df = pandas.DataFrame(np.random.randn(8, 2), columns=['a', 'b'])
In [112]: df['DateTime'] = pandas.date_range('2015-01-01', '2015-01-08', tz='US/Eastern')
In [113]: df.dtypes
Out [113]:
a float64
b float64
DateTime datetime64[ns, US/Eastern]
dtype: object
# creation of connection alchemy connection string omitted
In [114]: dtypes_ = {
...: 'a': sql.Float(precision=4),
...: 'b': sql.Float(precision=4),
...: 'DateTime': sql.DateTime(timezone=True)
...: }
In [115]: df.to_sql(
...: MYSQL_TABLE,
...: conn,
...: flavor='mysql',
...: schema=MSYQL_SCHEMA,
...: if_exists='append',
...: index=False,
...: index_label=None,
...: chunksize=None,
...: dtype=dtypes_
...: )
此代码抛出以下异常(包括最后的回溯):
/home/vagrant/anaconda2/lib/python2.7/site-packages/pandas/tseries/index.pyc in astype(self, dtype)
840 return Index(self.format(), name=self.name, dtype=object)
841 else: # pragma: no cover
--> 842 raise ValueError('Cannot cast DatetimeIndex to dtype %s' % dtype)
843
844 def _get_time_micros(self):
ValueError: Cannot cast DatetimeIndex to dtype datetime64[us]
我看过一些关于将 datetime64[ns, US/Eastern]
强制转换为字符串并插入的帖子。我宁愿在我的表中有正确的字段类型,也不愿使用 hack。另外,这似乎应该可行。
注意 datetime64[ns, US/Eastern]
不是 DataFrame
的索引。
关于如何使用 SQLALchemy 将时区感知 datetime64[ns]
数据类型插入 MySQL 有什么建议吗?
最佳答案
我建议将您的本地时区转换为 UTC,将转换后的时间戳保存为常规 datetime64
(不带时区),当您从数据库读回时 - 将其转换回您本地的时区。
演示:
from tzlocal import get_localzone # tzlocal needs to be extra installed
import pandas as pd
import pymysql
from sqlalchemy import create_engine
mytz = get_localzone() # it returns 'Europe/Berlin' (UTC +1) for me
df = pd.DataFrame(np.random.randn(8, 2), columns=['a', 'b'])
#df['DateTime'] = pd.date_range('2015-01-01', '2015-01-08', tz='US/Eastern')
df['DateTime'] = pd.date_range('2015-01-01', '2015-01-08', tz=mytz)
# convert my local TZ into UTC and remove time zone (localize)
df['DateTime'] = df['DateTime'].dt.tz_convert('UTC').dt.tz_localize(None)
它产生:
In [230]: df.dtypes
Out[230]:
a float64
b float64
DateTime datetime64[ns] # NOTE: there is _no_ TZ info
dtype: object
In [231]: df
Out[231]:
a b DateTime
0 0.050288 0.045425 2014-12-31 23:00:00
1 0.603057 -0.443899 2015-01-01 23:00:00
2 -0.874863 -1.185011 2015-01-02 23:00:00
3 0.446314 -0.301012 2015-01-03 23:00:00
4 -0.267889 -0.819698 2015-01-04 23:00:00
5 -0.888317 0.189641 2015-01-05 23:00:00
6 -0.985719 -0.962523 2015-01-06 23:00:00
7 -0.736928 -0.379683 2015-01-07 23:00:00
现在让我们将DF保存到MySQL DB中;
db_connection = 'mysql+pymysql://mysql_user:mysql_password@mysql_host/mysql_db'
engine = create_engine(db_connection)
#engine.execute("set time_zone='US/Eastern'") # this trick didn't work for me
df.to_sql('test_table_index', engine, if_exists='replace', index=False)
检查 MySQL 数据库:
mysql> select * from aaa;
+--------------------+--------------------+---------------------+
| a | b | DateTime |
+--------------------+--------------------+---------------------+
| 0.0502883957484278 | 0.045424787582407 | 2014-12-31 23:00:00 |
| 0.603057085374334 | -0.443899474872308 | 2015-01-01 23:00:00 |
| -0.874862846879629 | -1.18501101907713 | 2015-01-02 23:00:00 |
| 0.446314112615487 | -0.3010118937233 | 2015-01-03 23:00:00 |
| -0.267889181254187 | -0.819698158571756 | 2015-01-04 23:00:00 |
| -0.888316926203869 | 0.189640636565 | 2015-01-05 23:00:00 |
| -0.985719317488699 | -0.962523458724807 | 2015-01-06 23:00:00 |
| -0.736928170623884 | -0.37968341793291 | 2015-01-07 23:00:00 |
+--------------------+--------------------+---------------------+
8 rows in set (0.00 sec)
让我们从 MySQL DB 中读回它:
# read data back from MySQL
new = pd.read_sql('select * from aaa', engine)
现在是UTC TZ
In [221]: new
Out[221]:
a b DateTime
0 0.050288 0.045425 2014-12-31 23:00:00
1 0.603057 -0.443899 2015-01-01 23:00:00
2 -0.874863 -1.185011 2015-01-02 23:00:00
3 0.446314 -0.301012 2015-01-03 23:00:00
4 -0.267889 -0.819698 2015-01-04 23:00:00
5 -0.888317 0.189641 2015-01-05 23:00:00
6 -0.985719 -0.962523 2015-01-06 23:00:00
7 -0.736928 -0.379683 2015-01-07 23:00:00
将时间戳从 UTC 转换为我本地的 TZ:
new['DateTime'] = new['DateTime'].dt.tz_localize('UTC').dt.tz_convert(mytz)
In [223]: new
Out[223]:
a b DateTime
0 0.050288 0.045425 2015-01-01 00:00:00+01:00
1 0.603057 -0.443899 2015-01-02 00:00:00+01:00
2 -0.874863 -1.185011 2015-01-03 00:00:00+01:00
3 0.446314 -0.301012 2015-01-04 00:00:00+01:00
4 -0.267889 -0.819698 2015-01-05 00:00:00+01:00
5 -0.888317 0.189641 2015-01-06 00:00:00+01:00
6 -0.985719 -0.962523 2015-01-07 00:00:00+01:00
7 -0.736928 -0.379683 2015-01-08 00:00:00+01:00
关于python - 使用 SQLAlchemy 将 Timezone Aware datetime64[ns] 插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41777149/
我需要以 [+/-]hh:mm 格式保存手机的时区 我正在使用 TimeZone 类来处理这个问题,但我能得到的唯一格式如下: PST -05:00 GMT +02:00 我宁愿不对结果进行子串化,是
我正在尝试在 Node js 中使用 moment-timezone 来获取所有可用时区的列表,如下所示 - var moment = require('moment-timezone'); var
我正在使用以下代码将时区 (GMT-3) 转换为设备本地时区。 int hour=17,minute=0,day=12,month=6,year=2014; Calendar cal = new Gr
System.setProperty("user.timezone", "America/Chicago"); TimeZone.setDefault(TimeZone.getTimeZone("美国
我想从字符串初始化DateFormatter().timeZone,但是当我做类似的事情时 let dateFormatter = DateFormatter() dateFormatter.time
我通过存储日期组件字典在我的后端存储用户出生日期。它看起来像这样: { "day": 1, "month": 1, "year": 1970, "timeZone":
我一直在开发一个应用程序,它以下面给出的特定格式从服务器获取日期。 "2015-02-03 00:00:00" 我想使用 NSDateFormatter 以不同的 UI 格式显示它们但是当我更改时区时
我有什么 我有一个来自服务器的日期字符串,它的格式是 w3c 日期格式 2016-02-13T09:53:49.871Z 我的问题 当我将消息发布到服务器时,它显示的是 5 小时前而不是现在 我想要什
我正在将我的项目从 Django 1.8.2 升级到 1.9.7,我收到了这个警告: WARNINGS: my_app.my_model.date_available: (fields.W161) F
在下面的代码中: from datetime import datetime import pytz EDT = pytz.timezone('US/Eastern') d1 = datetime.n
我通过以下方式将服务器(Ubuntu 12.04)的时区更改为UTC: echo 'UTC' > /etc/timezone dpkg-reconfigure --frontend nonintera
我想获取洛杉矶的时区信息,现在10/10/2017是夏令时,但是我通过两种方式获取洛杉矶的时区得到了不同的结果。 public class TimeZoneDemo2 { public stati
我把它放在应用程序 Controller 中: before_filter :set_timezone def set_timezone Time.zone = current_user.time_
是否可以转换java.util.TimeZone字符串 sun.util.calendar.ZoneInfo[id=\"America/Los_Angeles\",offset=-28800000,d
当我写这段代码时: Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("EST"));
我正在使用 Java 8, 在我们的代码的前面,我们使用 sdf.setTimeZone(TimeZone.getTimeZone("PDT")); 转换为失败的美国太平洋地区(没有抛出任何错误,但转
我不断收到此警告:timezone of object (UTC) is different than current timezone ().我当前的时区是“EET”,如 Sys.timezone(
我正在我的网站上使用时刻时区转换器进行时区日期转换。默认情况下,我在 IST 中显示日期和时间。我有一个按钮可以转换用户时区中的给定时间。此按钮操作调用 moment js 并进行转换。到这里我没有问
我从服务响应中获得时区偏移量为“-5.00”,我需要在 UI 中将其格式化为 CST。我如何在 JavaScript 中转换它?我搜索了一下,不确定JavaScript中有没有直接的方法。 最佳答案
这个问题在这里已经有了答案: Converting string to datetime object (2 个答案) 关闭 6 年前。 我的主机有 UTC 时区,我正在尝试将 PDT 时间字符串转
我是一名优秀的程序员,十分优秀!