Last active
February 1, 2020 11:01
-
-
Save guerbai/e5fd4c49dfcc7f162c4a0bc762350a04 to your computer and use it in GitHub Desktop.
python时间的一些处理 #Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 获取昨天今天明天日期: | |
yesterday = time.strftime('%Y-%m-%d',time.localtime(time.time() - 24*60*60)) | |
today = time.strftime("%Y-%m-%d", time.localtime(time.time())) | |
tomorrow = time.strftime('%Y-%m-%d',time.localtime(time.time() + 24*60*60)) | |
# 字符串转时间戳与时间戳转字符串: | |
timeArray = time.strptime(atimestr, "%Y-%m-%d %H:%M:%S") | |
thistime = time.mktime(timeArray) | |
value = time.localtime(timestramp) | |
thistimestr = time.strftime('%Y-%m-%d %H:%M:%S', value) | |
# 获取现在时间格式化字符串: | |
utime = time.strftime("%Y-%m-%d %H:%M:%S") | |
# Python asctime()转化回来: | |
atime = 'Thu Nov 10 17:10:44 2016' | |
time.strptime(atime, "%a %b %d %H:%M:%S %Y") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# %Y-%m-%d %H:%M:%S | |
# YYYY-MM-DD | |
arrow.get(value).to('local').format('YYYY-MM-DD HH:mm:ss’) | |
# marshmallow处理时间序列化、反序列化: | |
# 输入为任意格式,输出为指定格式。 | |
class DateTimeField(fields.Field): | |
def _serialize(self, value, attr, obj): | |
return arrow.get(value).to('local').format('YYYY-MM-DD HH:mm:ss') | |
def _deserialize(self, value, attr, data): | |
return arrow.get(value).datetime |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import arrow | |
# 以东八区上海时间的第一秒为准. | |
def get_year_first_seconget_year_first_secondd(year): | |
year_str = str(year) + '-01-01' | |
return arrow.get(year_str).timestamp - 8 * 60 * 60 | |
def get_today_first_second(): | |
return arrow.get().timestamp - arrow.get().to('Asia/Shanghai').hour * 60 * 60 - arrow.get().minute * 60 - arrow.get().second | |
def get_month_first_second(year, month): | |
s = str(year) | |
if month < 10: | |
s += '-0' + str(month) | |
else: | |
s += '-' + str(month) | |
s += '-01' | |
return arrow.get(s).timestamp - 8 * 60 * 60 | |
def get_next_month_first_second(year, month): | |
if month == 12: | |
return get_month_first_second(year+1, 1) | |
else: | |
return get_month_first_second(year, month+1) | |
def get_this_week_first_second(): | |
weekday_today = arrow.get().to('Asia/Shanghai').weekday() | |
return arrow.get(get_today_first_second()).to('Asia/Shanghai').shift(days=-weekday_today).timestamp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment