Home > Backend Development > Python Tutorial > Introduction to data type time in Python (with code)

Introduction to data type time in Python (with code)

不言
Release: 2019-03-01 11:24:59
forward
3471 people have browsed it

This article brings you an introduction to data type time in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is the time data type?

The data structure representing the time type in Python is the time data type;

2.time Module

import time
# 获取当前时间的时间戳
print(time.time())   #输出:1548742426.1698806

# 返回当前时间的元组
t = time.localtime()
print(t)
#输出:time.struct_time(tm_year=2019, tm_mon=1, tm_mday=29, tm_hour=14, tm_min=14, tm_sec=17, tm_wday=1, tm_yday=29, tm_isdst=0)


# 将当前时间元组转变为字符串
print(time.asctime(time.localtime()))  #输出:Tue Jan 29 14:15:51 2019

# # 格式化字符串
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))    #输出:2019-01-29 14:16:08
# # 将字符串转为时间元组

print(time.strptime('2018-11-27 08:08:08', '%Y-%m-%d %H:%M:%S'))  
#输出:time.struct_time(tm_year=2018, tm_mon=11, tm_mday=27, tm_hour=8, tm_min=8, tm_sec=8, tm_wday=1, tm_yday=331, tm_isdst=-1)

# sleep方法, 会占用cpu时间片
print(time.sleep(5))   #5秒后输出:None

# 打印日历
import calendar
print(calendar.month(2019, 1))   #输出:2019年1月的日历
Copy after login

Timestamp: It is the number of seconds from 0:00:00 on January 1, 1970 in the 0 time zone to the given date and time (floating point type ; , the next three digits are microseconds, usually milliseconds are enough;

localtime method: Returns a tuple of the current time (including year, month, day, hour, minute, second, etc.);

asctime method: Convert the current time tuple into a string (time format in European and American countries);

strftime method: Format string;

strptime method: Contrary to the strftime method, it is used to convert a string into a time tuple;

sleep method: It will occupy cpu time slice (that is, let the entire thread pause for some time);

Print calendar: import the calendar module, and then call the month method;

3.datetime module

The datetime module in python provides the function of operating date and time. The five core objects provided by this module are: datetime (time date type), date (date type), time (time type) ), tzinfo (time zone type), timedelta (time difference type);

(1) datetime type

from datetime import datetime
# 1: 构建一个指定日期和时间的datetime对象
today = datetime(year=2019,month=1,day=29,hour=14,minute=22,second=54)
print(today)  #输出:2019-01-29 14:22:54

#获取当前日期时间,输出类型为datetime
now = datetime.now()
print(now,type(now))  #输出:2019-01-29 14:23:35.408583 <class &#39;datetime.datetime&#39;>

d_now = datetime.now()
# datetime类型转字符串
d_str = d_now.strftime('%Y-%m-%d %H:%M:%S')
print(d_str,type(d_str))   #输出:2019-01-29 14:26:12 <class &#39;str&#39;>
# 字符串转datetime类型
d_type = datetime.strptime(d_str,'%Y-%m-%d %H:%M:%S')
print(d_type,type(d_type))  #输出:2019-01-29 14:26:12 <class &#39;datetime.datetime&#39;>

# 计算时间戳
timestamp = d_type.timestamp()
print(timestamp)  #输出:1548743501.0

# 计算时间戳
timestamp = d_type.timestamp()
print(timestamp)      #输出:1548743935.0

# 通过时间戳获取datetime对象   
d_type = datetime.fromtimestamp(1543408827)
print(d_type, type(d_type))  #输出:2018-11-28 20:40:27 <class &#39;datetime.datetime&#39;>
Copy after login

Used to convert datetime type to string strftime method, use strptime method to convert string to datetime type;

  • timestamp method: calculate timestamp;

  • fromtimestamp method: obtain by timestamp datetime object;

  • (2) date type
from datetime import date
data_today = date(year=2018, month=11, day=29)
print(data_today)  #输出:2018-11-29
Copy after login

Import the date module and instantiate the date;

  • (3) time type
from datetime import time
now_time = time(hour=8, minute=30, second=10)
print(now_time, type(now_time))  #输出:20:30:10 <class &#39;datetime.time&#39;>
Copy after login

Import time type and instantiate time;

  • (4) timedelta type
from datetime import datetime, timedelta
# 时间间隔可以通过相减得到
now = datetime.now()
before_datatime = datetime(year=2018, month=11, day=20, hour=8, minute=20, second=20)
delta = now - before_datatime
print(delta, type(delta))   #输出:70 days, 6:22:37.340041 <class &#39;datetime.timedelta&#39;>

# 可以初始化时间间隔
delta_days = timedelta(days=7)
print(delta_days, type(delta_days))  #输出:7 days, 0:00:00 <class &#39;datetime.timedelta&#39;>

# 可以通过时间间隔得到将来的时间 
future_datetime = now + delta_days
print(future_datetime)    #输出:2019-02-05 14:43:54.582315
Copy after login

The timedelta object represents a time period. The timedelta object can be obtained by manual instantiation or subtraction;

  • (5)tzinfo type
from datetime import datetime
import pytz
utc_tz = pytz.timezone('UTC')
print(pytz.country_timezones('cn'))  # 显示中国时区的城市   #输出:['Asia/Shanghai', 'Asia/Urumqi']
print(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', 'America/Indiana/Knox', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/North_Dakota/Beulah', 'America/Denver', 'America/Boise', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Sitka', 'America/Metlakatla', 'America/Yakutat', 'America/Nome', 'America/Adak', 'Pacific/Honolulu']

# # 获取时区
china_tz = pytz.timezone('Asia/Shanghai')
america_tz = pytz.timezone('America/New_York')
# # 获取城市本地时间
china_local_time = datetime.now(china_tz) # 东八区
america_local_time = datetime.now(america_tz) # 西五区
print(china_local_time)   #输出:2019-01-29 14:51:51.252579+08:00
print(america_local_time)  #输出:2019-01-29 14:51:51.252579+08:00
Copy after login

Install the pytz package: Enter the project and execute the pip install pytz command;

  • Get the time zone: pytz.timezone (region name);

  • Get the city local time: datetime.now (time zone name);

The above is the detailed content of Introduction to data type time in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template