Hướng dẫn python typing date

Python Datetime


A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

Nội dung chính

  • Python Datetime
  • Date Output
  • Creating Date Objects
  • The strftime() Method
  • Introduction
  • The datetime Module
  • Converting Dates to Strings with strftime
  • Converting Strings to Dates with strptime
  • How do I change date format from YYYY
  • How do I change date format to one in Python?
  • How do you change a date format from a string in Python?
  • How do you format a date?

Example

Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()
print(x)

Try it Yourself »


Date Output

When we execute the code from the example above the result will be:

The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date object.

Here are a few examples, you will learn more about them later in this chapter:

Example

Return the year and name of weekday:

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

Try it Yourself »


Creating Date Objects

To create a date, we can use the datetime() class (constructor) of the datetime module.

The datetime() class requires three parameters to create a date: year, month, day.

Example

Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

Try it Yourself »

The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).



The strftime() Method

The datetime object has a method for formatting date objects into readable strings.

The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:

Example

Display the name of the month:

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))

Try it Yourself »

A reference of all the legal format codes:

DirectiveDescriptionExampleTry it
%a Weekday, short version Wed Try it »
%A Weekday, full version Wednesday Try it »
%w Weekday as a number 0-6, 0 is Sunday 3 Try it »
%d Day of month 01-31 31 Try it »
%b Month name, short version Dec Try it »
%B Month name, full version December Try it »
%m Month as a number 01-12 12 Try it »
%y Year, short version, without century 18 Try it »
%Y Year, full version 2018 Try it »
%H Hour 00-23 17 Try it »
%I Hour 00-12 05 Try it »
%p AM/PM PM Try it »
%M Minute 00-59 41 Try it »
%S Second 00-59 08 Try it »
%f Microsecond 000000-999999 548513 Try it »
%z UTC offset +0100
%Z Timezone CST
%j Day number of year 001-366 365 Try it »
%U Week number of year, Sunday as the first day of week, 00-53 52 Try it »
%W Week number of year, Monday as the first day of week, 00-53 52 Try it »
%c Local version of date and time Mon Dec 31 17:41:00 2018 Try it »
%C Century 20 Try it »
%x Local version of date 12/31/18 Try it »
%X Local version of time 17:41:00 Try it »
%% A % character % Try it »
%G ISO 8601 year 2018 Try it »
%u ISO 8601 weekday (1-7) 1 Try it »
%V ISO 8601 weeknumber (01-53) 01 Try it »


Introduction

Python comes with a variety of useful objects that can be used out of the box. Date objects are examples of such objects. Date types are difficult to manipulate from scratch, due to the complexity of dates and times. However, Python date objects make it extremely easy to convert dates into the desirable string formats.

Date formatting is one of the most important tasks that you will face as a programmer. Different regions around the world have different ways of representing dates/times, therefore your goal as a programmer is to present the date values in a way that is readable to the users.

For example, you may need to represent a date value numerically like "02-23-2018". On the flip side, you may need to write the same date value in a longer textual format like "Feb 23, 2018". In another scenario, you may want to extract the month in string format from a numerically formated date value.

In this article, we will study different types of date objects along with their functionalities.

The datetime Module

Python's datetime module, as you probably guessed, contains methods that can be used to work with date and time values. To use this module, we first import it via the import statement as follows:

import datetime

We can represent time values using the time class. The attributes for the time class include the hour, minute, second and microsecond.

The arguments for the time class are optional. Although if you don't specify any argument you will get back a time of 0, which is unlikely to be what you need most of the time.

For example, to initialize a time object with a value of 1 hour, 10 minutes, 20 seconds and 13 microseconds, we can run the following command:

t = datetime.time(1, 10, 20, 13)

To see the time, let's use the print function:

print(t)

Output:

01:10:20.000013

You may need to see either the hour, minute, second, or microsecond only, here is how you can do so:

print('hour:', t.hour)

Output:

hour: 1

The minutes, seconds and microseconds for the above time can be retrieved as follows:

print('Minutes:', t.minute)
print('Seconds:', t.second)
print('Microsecond:', t.microsecond)

Output:

Minutes: 10
Seconds: 20
Microseconds: 13

The values for the calendar date can be represented via the date class. The instances will have attributes for year, month, and day.

Let us call the today method to see today's date:

import datetime

today = datetime.date.today()
print(today)

Output:

2018-09-15

The code will return the date for today, therefore the output you see will depend on the day you run the above script.

Now let's call the ctime method to print the date in another format:

print('ctime:', today.ctime())

Output:

ctime: Sat Sep 15 00:00:00 2018

The ctime method uses a longer date-time format than the examples we saw before. This method is primarily used for converting Unix-time (the number of seconds since Jan. 1st, 1970) to a string format.

And here is how we can display the year, the month, and the day using the date class:

print('Year:', today.year)
print('Month:', today.month)
print('Day :', today.day)

Output

Year: 2018
Month: 9
Day : 15

Converting Dates to Strings with strftime

Now that you know how to create Date and Time objects, let us learn how to format them into more readable strings.

To achieve this, we will be using the strftime method. This method helps us convert date objects into readable strings. It takes two parameters, as shown in the following syntax:

time.strftime(format, t)

The first parameter is the format string, while the second parameter is the time to be formatted, which is optional.

This method can also be used on a datetime object directly, as shown in the following example:

import datetime

x = datetime.datetime(2018, 9, 15)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output:

Sep 15 2018 00:00:00

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

We have used the following character strings to format the date:

  • %b: Returns the first three characters of the month name. In our example, it returned "Sep"
  • %d: Returns day of the month, from 1 to 31. In our example, it returned "15".
  • %Y: Returns the year in four-digit format. In our example, it returned "2018".
  • %H: Returns the hour. In our example, it returned "00".
  • %M: Returns the minute, from 00 to 59. In our example, it returned "00".
  • %S: Returns the second, from 00 to 59. In our example, it returned "00".

We did not pass a time, hence the values for time are all "00". The following example shows how the time can be formatted as well:

import datetime

x = datetime.datetime(2018, 9, 15, 12, 45, 35)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output:

Sep 15 2018 12:45:35

The Complete Character Code List

Other than the character strings given above, the strftime method takes several other directives for formatting date values:

  • %a: Returns the first three characters of the weekday, e.g. Wed.
  • %A: Returns the full name of the weekday, e.g. Wednesday.
  • %B: Returns the full name of the month, e.g. September.
  • %w: Returns the weekday as a number, from 0 to 6, with Sunday being 0.
  • %m: Returns the month as a number, from 01 to 12.
  • %p: Returns AM/PM for time.
  • %y: Returns the year in two-digit format, that is, without the century. For example, "18" instead of "2018".
  • %f: Returns microsecond from 000000 to 999999.
  • %Z: Returns the timezone.
  • %z: Returns UTC offset.
  • %j: Returns the number of the day in the year, from 001 to 366.
  • %W: Returns the week number of the year, from 00 to 53, with Monday being counted as the first day of the week.
  • %U: Returns the week number of the year, from 00 to 53, with Sunday counted as the first day of each week.
  • %c: Returns the local date and time version.
  • %x: Returns the local version of date.
  • %X: Returns the local version of time.

Consider the following example:

import datetime

x = datetime.datetime(2018, 9, 15)

print(x.strftime('%b/%d/%Y'))

Output:

Sep/15/2018

And here is how you can get the month only:

print(x.strftime('%B'))

Output:

September

Let us display the year:

print(x.strftime('%Y'))

Output:

2018

In this example we have used the format code %Y. Notice that the Y is in uppercase. Now write it in lowercase:

print(x.strftime('%y'))

Output:

18

This time, the century has been omitted. As you can see, with these formatting codes you can represent the date-time in just about any form that you'd like.

Converting Strings to Dates with strptime

The strftime method helped us convert date objects into more readable strings. The strptime method does the opposite, that is, it takes strings and converts them into date objects that Python can understand.

Here is the syntax for the method:

datetime.strptime(string, format)

The string parameter is the value in string format that we want to convert into date format. The format parameter is the directive specifying the format to be taken by the date after the conversion.

For example, let's say we need to convert the string "9/15/18" into a datetime object.

Let's first import the datetime module. We will use the from keyword in order to be able to reference the specific module functions without the dot format:

from datetime import datetime

We can then define the date in the form of a string:

str = '9/15/18'

Python will not be able to understand the above string as a datetime until we convert it to an actual datetime object. We can successfully do so by calling the strptime method.

Execute the following command to convert the string:

date_object = datetime.strptime(str, '%m/%d/%y')

Let's now call the print function to display the string in datetime format:

print(date_object)

Output:

2018-09-15 00:00:00

As you can see, the conversion was successful!

You can see that the forward slash "/" has been used to separate the various elements of the string. This tells the strptime method what format our date is in, which in our case "/" is used as a separator.

But what if the day/month/year was separated by a "-"? Here is how you'd handle that:

from datetime import datetime

str = '9-15-18'
date_object = datetime.strptime(str, '%m-%d-%y')

print(date_object)

Output:

2018-09-15 00:00:00

And again, thanks to the format specifier the strptime method was able to parse our date and convert it to a date object.

Conclusion

In this article, we studied how to format dates in Python. We saw how the datetime module in Python can be used for the manipulation of date and time values. The module contains a number of classes that can be used for this purpose. For example, the time class is used to represent time values while the date class is used to represent calendar date values.

How do I change date format from YYYY

We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime..

input is the string datetime..

format is the format – 'yyyy-mm-dd'.

datetime is the module..

How do I change date format to one in Python?

Thanks for the answer. ... .

You can replace NaN value in the column by df['date'] = df['date'].fillna(0) then df['date'] = df['date'].apply(lambda x: pd.to_datetime(x).strftime('%d/%m/%Y') if x != 0 else x) And you need to do handle the zero entry in the date column according to your requirement..

How do you change a date format from a string in Python?

from datetime import datetime..

date_time_str = '18/09/19 01:55:19'.

date_time_obj = datetime. strptime(date_time_str, '%d/%m/%y %H:%M:%S').

print ("The type of the date is now", type(date_time_obj)).

How do you format a date?

The international standard recommends writing the date as year, then month, then the day: YYYY-MM-DD.