例如: 我有一个日期字符串
2018-02-17 16:15:36.519 PST
我如何转换成UTC中的isoformat,如下所示
2018-02-18T00:15:36.519Z
我试过这个
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
print parse(d1)
it prints like this. How do i convert it to UTC with Z at the end.
2018-02-17 16:15:36.519000-08:00
修改 使用python 2.7。
import dateutil
import pytz
from dateutil.parser import parse
d1='2018-02-17 16:15:36.519 PST'
d2=dateutil.parser.parse(d1)
d2.replace(tzinfo=pytz.utc) - d2.utcoffset()
d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat()
print d3
然后根据建议用Z格式化
答案 0 :(得分:3)
将时区缩写(PST
)解析为时区感知日期时间对象:
import dateparser # pip install dateparser
pst_dt = dateparser.parse('2018-02-17 16:15:36.519 PST')
# -> datetime.datetime(2018, 2, 17, 16, 15, 36, 519000, tzinfo=<StaticTzInfo 'PST'>)
将时间转换为UTC时区:
import datetime as DT
utc_dt = pst_dt.astimezone(DT.timezone.utc)
# -> datetime.datetime(2018, 2, 18, 0, 15, 36, 519000, tzinfo=datetime.timezone.utc)
以所需格式打印:
print(utc_dt.isoformat()) # -> 2018-02-18T00:15:36.519000+00:00
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # -> 2018-02-18T00:15:36.519000Z
在Python 2.7上没有DT.timezone.utc
:
utc_naive = psd_dt.replace(tzinfo=None) - psd_dt.utcoffset()
print utc_naive.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# -> 2018-02-18T00:15:36.519000Z
注意:在一般情况下,时区缩写(例如PST
)可能不明确。见Parsing date/time string with timezone abbreviated name in Python?
在您的特定情况下,时间字符串对应于唯一的UTC时间:
>>> from collections import defaultdict
>>> import datetime as DT
>>> import pytz
>>> naive_dt, tzabbr = DT.datetime(2018, 2, 17, 16, 15, 36, 519000), 'PST'
>>> utc_times = defaultdict(list)
>>> for zone in pytz.all_timezones:
... dt = pytz.timezone(zone).localize(naive_dt, is_dst=None)
... if dt.tzname() == tzabbr: # same timezone abbreviation
... utc_times[dt.astimezone(pytz.utc)].append(zone)
>>> for utc_dt, timezones in utc_times.items():
... print(f'{utc_dt:%c %Z}', *timezones, sep='\n\t')
Sun Feb 18 00:15:36 2018 UTC
America/Dawson
America/Ensenada
America/Los_Angeles
America/Santa_Isabel
America/Tijuana
America/Vancouver
America/Whitehorse
Canada/Pacific
Canada/Yukon
Mexico/BajaNorte
PST8PDT
US/Pacific
US/Pacific-New
答案 1 :(得分:0)
这是python2.7的演示代码,仅供参考,
import { Component, Inject } from "@angular/core";
import { ModalController } from "@ionic/angular";
import { WorkspacesComponent } from "../workspaces/workspaces.component";
import { Workspace } from "../models/workspace.model";
@Component({
selector: "app-workspace-modal",
templateUrl: "./workspace-modal.component.html",
styles: [],
})
export class WorkspaceModalComponent {
constructor(public modalController: ModalController, public data: any) {}
/**
* CLOSE THE MODAL ON CLICK
*/
async closeWorkspaceModal() {
await this.modalController.dismiss();
}
}