from datetime import datetime
def utc2local( utc_dtm ):
# UTC 时间转本地时间( +8:00 )
local_tm = datetime.fromtimestamp( 0 )
utc_tm = datetime.utcfromtimestamp( 0 )
offset = local_tm - utc_tm
return utc_dtm + offset
def local2utc( local_dtm ):
# 本地时间转 UTC 时间( -8:00 )
return datetime.utcfromtimestamp( local_dtm.timestamp() )
if __name__ == "__main__":
# utc_tm = datetime.utcnow()
utc_tm = datetime( 2012, 10, 26, 10, 00, 00 )
print( "src utc time:\t", utc_tm.strftime("%Y-%m-%d %H:%M:%S") )
# UTC 转本地
local_tm = utc2local(utc_tm)
print( "tran loc time:\t", local_tm.strftime("%Y-%m-%d %H:%M:%S") )
# 本地转 UTC
utc_tran = local2utc(local_tm)
print( "tran utc time:\t", utc_tran.strftime("%Y-%m-%d %H:%M:%S") )
flask-moment的使用
在hello.py中初始化Flask-Moment
from flask_moment import Moment
moment = Moment(app)
在templates/base.html中引入moment.js库
{% block scripts %}
{{ super() }}
{{ moment.include_moment(local_js=url_for('static', filename='js/moment-with-locales.min.js')) }}
{% endblock %}
在hello.py中加入一个datetime变量
from datetime import datetime
@app.route('/')
def index():
return render_template('index.html',current_time=datetime.utcnow())
在templates/index.html当中渲染current_time
{% extends 'base.html' %}
{% block page_content %}
<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
{% endblock %}
moment-with-locales.min.js