postgresql - How do you JSON Marshall a pq.NullTime in UTC rather than the local timezone?
问题描述
I have dates in postgres table. The dates are stored with a UTC timezone.
Example from python.
roster = Roster.objects.get(id=266438)
roster.start_timestamp
Out[11]: datetime.datetime(2018, 9, 7, 15, 0, tzinfo=<UTC>)
When I marshall these dates from within go lib/pq my local time zone is somehow being applied.
func (nt *pq.NullTime) MarshalJSON() ([]byte, error) {
if !nt.Valid {
return []byte("\"\""), nil
}
val := fmt.Sprintf("\"%s\"", nt.Time.Format("01/02/2006 15:04:05"))
fmt.Println("Marshalling FMPDateTime", nt, val)
return []byte(val), nil
}
Example log:
Marshalling DateTime &{2018-09-08 00:30:00 +0930 ACST true} "09/08/2018 00:30:00"
2018-09-08 00:30:00 +0930 ACST is 2018-09-07 15:00:00 UTC.
How do you JSON Marshall a pq.NullTime in UTC rather than the local timezone?
解决方案
库通常time.Time
使用本地时区构造值,但时间瞬间仍然相同,因此您不必担心。
如果您想专门显示/输出 UTC 时区的时间,则将您的时间“切换”到 UTC 时区。为此,您可以使用以下Time.UTC()
方法:
val := fmt.Sprintf("\"%s\"", nt.Time.UTC().Format("01/02/2006 15:04:05"))
就这样。
另请注意,如果您NullTime
的无效,我宁愿输出 JSONnull
而不是空字符串。
推荐阅读
- rsa - 使用 RSA 公钥加密时,GPG 使用什么填充方案?
- jaxb - jaxb:前缀和后缀被忽略
- keystonejs - 如何根据 KeystoneJS Next 另一个字段的值在管理 UI 中显示/隐藏字段?
- android - Android资源桶及解析策略
- oracle - Apex.message.confirm。如何从确认 javascript 中隐藏 IP 地址
- reactjs - React-Select 和用户事件库
- flutter - Flutter Streams:.asBroadcast 的更好替代方案?使用行为主题?
- google-bigquery - BigQuery 中缺少 ga_session_id 的 GP 事件
- angular - 在 rxjs 中调用下一个方法另一个私有方法
- python - 如何将我的过滤器表单连接到过滤视图 Django?