当前位置 : 主页 > 编程语言 > python >

Python datetime模块使用方法小结

来源:互联网 收集:自由互联 发布时间:2021-04-02
datetime模块 当前日期 datetime.date.today() datetime.date(2020, 4, 24) 转换元祖 datetime.date.timetuple(datetime.date.today()) time.struct_time(tm_year=2020, tm_mon=4, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=

datetime模块

当前日期

datetime.date.today()
datetime.date(2020, 4, 24)

转换元祖

>>> datetime.date.timetuple(datetime.date.today())
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=115, tm_isdst=-1)

当前时间,精确至毫秒

>>> datetime.datetime.now()
datetime.datetime(2020, 4, 24, 10, 54, 20, 538999)

时间差

>>> t1 = datetime.datetime.now()

>>> datetime.timedelta(days=3)
datetime.timedelta(days=3)
>>> t1 - datetime.timedelta(days=3)
datetime.datetime(2020, 4, 21, 10, 57, 26, 181212)

>>> t1 - datetime.timedelta(days=3,minutes=5)
datetime.datetime(2020, 4, 21, 10, 52, 26, 181212)

替换

>>> t1
datetime.datetime(2020, 4, 24, 10, 57, 26, 181212)
>>> t1.replace(year=2015)
datetime.datetime(2015, 4, 24, 10, 57, 26, 181212)

>>> t1.replace(year=2016,month=3,minute=2)
datetime.datetime(2016, 3, 24, 10, 2, 26, 181212)

帮助调用

help(datetime.datetime())

时区

>>> import pytz
>>> pytz.timezone("Asia/shanghai")
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>

 >>> datetime.datetime.now(tz=pytz.timezone("Asia/shanghai"))
datetime.datetime(2020, 4, 24, 11, 14, 47, 215302, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)


# 中国所拥有的时区
>>> pytz.country_timezones('cn')
['Asia/Shanghai', 'Asia/Urumqi']


# 美国所拥有的时区

>>> pytz.country_timezones('us')
['America/New_York', 'America/Detroit', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Indiana/Indianapolis', 'America/Indiana/Vincennes',
 'America/Indiana/Winamac', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Vevay', 'America/Chicago', 'America/Indiana/Tell_City', 'Ame
rica/Indiana/Knox', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/North_Dakota/Beulah', 'America/Denver', 'Americ
a/Boise', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Sitka', 'America/Metlakatla', 'America/Yakutat', 'America/Nome
', 'America/Adak', 'Pacific/Honolulu']
 >>> datetime.datetime.now(tz=pytz.timezone("Asia/shanghai"))  #上海时区
datetime.datetime(2020, 4, 24, 11, 23, 14, 871634, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>> datetime.datetime.now(tz=pytz.timezone("America/New_York")) # 纽约时区
datetime.datetime(2020, 4, 23, 23, 23, 32, 743094, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
>>> datetime.datetime.now(tz=pytz.timezone("Asia/Saigon"))  # 胡志明市 越南
datetime.datetime(2020, 4, 24, 10, 24, 53, 456136, tzinfo=<DstTzInfo 'Asia/Saigon' +07+7:00:00 STD>)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论