Python datetime now | Module | TimeZone | Examples

In python getting a time and date can do by to import one of them modules DateTime and time. Python DateTime is more preferable to get date and time.  Both time and DateTime modules are inbuilt, you don’t need any 3rd party library.

In this tutorial, you will learn how to get the current time, today’s date, and python DateTime timezone overview with an example.

Python datetime now | Module | TimeZone | Examples

Example of Python DateTime now

The example of getting the current date and time in python using the DateTime module and class.

Output: 2018-10-12 16:04:42.036760

The output is in the format of YYYY-MM-DD HH:MM:SS:MS

To complete detailed example must read: Python Date Function

Python Time now Example

Output: Time : 1539340637.700062
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=12, tm_hour=16, tm_min=7, tm_sec=17, tm_wday=4, tm_yday=285, tm_isdst=0)

Here is seperate tutorial on time function –  Python Time Function

How to get a Specific string from the DateTime object

Using strftime () Method you can get a specific string from a datetime object, for an example year, day, month etc.

here is an example of getting the full name of weekday from today date

Output: Friday

Format codes in strftime:

Here is import format code for strftime.

%aShort name of weekdayFri
%AFull name of WeekdayFriday
%wWeekday as a number 0-6, 0 is Sunday – 0 Monday – 1 …5
%dDay of month 01-3101
%bMonth name, short versionOct
%BMonth name, full versionOctober
%mMonth as a number 01-1210
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2300
%IHour 00-1212
%MMinute 00-5938
%SSecond 00-5901
%fMicrosecond 000000-999999844628
%zUTC offset+0100
%jDay number of year 001-366283
%UWeek number of year, Sunday as the first day of the week, 00-5340
%WWeek number of year, Monday as the first day of the week, 00-5341
%cLocal version of date and timeWed Oct 10 03:38:01 2018
%xLocal version of date10/10/18
%XLocal version of time03:38:01
%%A % character%

Note: Examples are based on datetime.datetime(2018, 10, 10, 3, 38, 1, 844628)

Tutorial for a strftime method: Python strftime Function

Python DateTime TimeZone

Getting current timezone will be none, you have to use the import module for a date or add timezone using tzinfo.

Output: None

QA: Difference between two dates.

You can calculate a number of days between two dates using date function like this.

Output: 404

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.