41 common built-in modules datetime

Source: Internet
Author: User
Tags epoch time local time timedelta

DateTime is the standard library for Python to process dates and times.

Get the current date and time

Let's look at how to get the current date and time:

 from datetime import datetime>>> now = DateTime.Now () # Gets the current datetime>>> Print /c3>----:07.198690>>> print (type (now)) <class'datetime.datetime'>

Note that the module datetime datetime also contains a datetime class that is from datetime import datetime imported by datetime this class.

If you import only import datetime , you must refer to the full name datetime.datetime .

datetime.now()Returns the current date and time, whose type is datetime .

Gets the specified date and time

To specify a date and time, we construct one directly with the parameter datetime :

 from datetime import datetime>>> dt = datetime420  # Create a datetime>>> print (dt) by a specified datetime-- :xx 
DateTime conversion to Timestamp

In a computer, time is actually represented by a number. We call the time of the January 1, 1970 00:00:00 utc+00:00 time zone The epoch time, which is recorded as 0 (the time before 1970 is timestamp negative), and the current is the number of seconds relative to the epoch. Called timestamp.

You can think:

0 1970-1-1, xx: utc+ 0: xx

The corresponding Beijing time is:

0 1970-1-1: xx: utc+ 8:00 

The value of the visible timestamp has nothing to do with the time zone, because once timestamp is determined, its UTC time is determined and the time to convert to any time zone is fully deterministic, which is why the current time of the computer storage is represented by timestamp. Because computers around the world are timestamp at any time (assuming time is calibrated).

To datetime convert a type to timestamp, simply call the timestamp() method:

 from datetime import datetime>>> dt = datetime420  # Create datetime>>> dt.timestamp () # with a specified datetime convert timestamp to datetime1429417200.0 

Note that Python's timestamp is a floating-point number. If there are decimal digits, the decimal place represents the number of milliseconds.

Some programming languages, such as Java and JavaScript, timestamp use integers to represent the number of milliseconds, in which case you need to divide timestamp by 1000 to get a python floating point representation.

Timestamp conversion to DateTime

To convert timestamp to datetime , use datetime the method provided fromtimestamp() :

 from datetime import DateTime 1429417200.0>>> print (Datetime.fromtimestamp (t))-19  :xx 

Note that timestamp is a floating-point number that does not have a time zone concept, and datetime is a time zone. The conversion is done in timestamp and local time.

Local time refers to the time zone set by the current operating system. For example, when the Beijing time zone is East 8, local time:

$--£º

Timestamp can also be converted directly to the UTC standard Time zone:

 from datetime import DateTime 1429417200.0>>> print (Datetime.fromtimestamp (t)) # local time -Geneva-  :xx>>> print (Datetime.utcfromtimestamp (t)) # UTC Time (+)-Geneva: 
Str converted to DateTime

Many times, the date and time entered by the user is a string, and to process the date and time, Str must first be converted to DateTime. The conversion method is datetime.strptime() implemented by implementing a format string that requires a date and time:

 from datetime import datetime>>> cday = datetime.strptime ('2015-6-1 18:19:59'  '%y-%m-%d%h:%m:%s')>>> Print (cday)- -£º

The string ‘%Y-%m-%d %H:%M:%S‘ specifies the format of the date and time part. Please refer to the Python documentation for detailed instructions.

Note the converted DateTime does not have time zone information.

DateTime conversion to STR

If you already have a DateTime object and you want to format it as a string to display to the user, you need to convert to STR, and the conversion method is strftime() implemented by implementing a format string that also requires a date and time:

 from datetime import datetime>>> now = DateTime.Now ()>>> print (Now.strftime ('  %a,%b%d%h:%m':
DateTime plus minus

The addition and subtraction of dates and times is actually the calculation of datetime backwards or forwards, resulting in a new DateTime. Add and subtract can be used directly with the + - operator, but this class needs to be imported timedelta :

>>> fromdatetime import datetime, Timedelta>>> now =DateTime.Now ()>>>Nowdatetime.datetime ( -,5, -, -, $,3,540997)>>> now + timedelta (hours=Ten) Datetime.datetime ( -,5, +,2, $,3,540997)>>> Now-timedelta (days=1) Datetime.datetime ( -,5, -, -, $,3,540997)>>> now + timedelta (days=2, hours= A) Datetime.datetime ( -,5, +,4, $,3,540997)

Visible, using timedelta you can easily figure out the moment before and after a few days.

local time converted to UTC time

local time is the time when the system sets a time zone, such as when Beijing time is the utc+8:00 time zone, and UTC time refers to the time of the utc+0:00 time zone.

A datetime type has a time zone attribute tzinfo , but the default is None , so it is not possible to distinguish datetime which time zone this is, unless you force datetime a time zone to be set:

>>> fromdatetime import datetime, Timedelta, timezone>>> tz_utc_8 = TimeZone (Timedelta (hours=8) # Create Time zone utc+8:xx>>> now =DateTime.Now ()>>>Nowdatetime.datetime ( -,5, -, -,2,Ten,871012)>>> dt = Now.replace (tzinfo=tz_utc_8) # Force set to utc+8:xx>>>Dtdatetime.datetime ( -,5, -, -,2,Ten,871012, Tzinfo=datetime.timezone (Datetime.timedelta (0,28800)))

If the system time zone happens to be utc+8:00, then the above code is correct, otherwise, it cannot be forced to be set to the utc+8:00 time zone.

Time zone Conversion

We can start by utcnow() getting the current UTC time and then converting to any time zone:

# get UTC time, and force set time zone to utc+0:xx:>>> Utc_dt = Datetime.utcnow (). Replace (tzinfo=TIMEZONE.UTC)>>>print (UTC_DT) -- to- -  the: to:12.377316+xx:xx# Astimezone () will convert time zone to Beijing time:>>> Bj_dt = Utc_dt.astimezone (TimeZone (Timedelta (hours=8)))>>>print (BJ_DT) -- to- -  -: to:12.377316+ ,:xx# Astimezone () will convert time zone to Tokyo time:>>> Tokyo_dt = Utc_dt.astimezone (TimeZone (Timedelta (hours=9)))>>>print (TOKYO_DT) -- to- -  -: to:12.377316+ the:xx# Astimezone () convert Bj_dt to Tokyo time:>>> TOKYO_DT2 = Bj_dt.astimezone (TimeZone (Timedelta (hours=9)))>>>print (TOKYO_DT2) -- to- -  -: to:12.377316+ the:xx

The key to the time zone conversion is that when you get one datetime , you know its correct time zone, and then force the time zone to be the base time.

With a time zone datetime , astimezone() you can convert to any time zone by using the method.

Note: It is not necessary to convert from the utc+0:00 time zone to a different time zone, and any zone-band datetime can be converted correctly, such as bj_dt tokyo_dt the conversion described above.

Summary

datetimeThe time that is expressed requires time zone information to determine a specific time, otherwise it can only be considered local time.

If you want to store datetime it, the best way is to convert it to timestamp, because the value of timestamp is completely unrelated to the time zone.

Practice

Suppose you get the date and time that the user entered, as 2015-1-21 9:01:30 well as a time zone information such as UTC+5:00 , str write a function to convert it to timestamp:

Reference source

use_datetime.py

41 common built-in modules datetime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.