Python pendulum to datetime

Python Date Time Formatting with Pendulum

This Python Pendulum tutorial to show you how to format a DateTime instance as a string using Pendulum package. We will learn to use difference common methods to format string as well as using formatter method format() and strftime().

Table of contents

Install Pendulum package

Installing the Pendulum package using the below command.

Format DateTime string using common format methods

The following methods to format a DateTime instance as a string.

  • to_date_string() to format the DateTime instance as date.
  • to_formatted_date_string() to format the DateTime instance as readable date.
  • to_time_string() to format the DateTime instance as time.
  • to_datetime_string() to format the DateTime instance as date and time.
  • to_day_datetime_string() to format the DateTime instance as day, date and time in English.
  • to_iso8601_string() to format the DateTime instance as ISO 8601 format.
  • to_w3c_string() to format the DateTime instance as W3C format.
  • to_atom_string() to format the DateTime instance as ATOM format.
  • to_cookie_string() to format the DateTime instance as cookie format.
  • to_rss_string() to format the DateTime instance as RSS format.
  • to_rfc1036_string() to format the DateTime instance as RFC 1036 format.
  • to_rfc1123_string() to format the DateTime instance as RFC 1123 format.
  • to_rfc2822_string() to format the DateTime instance as RFC 2822 format.
  • to_rfc3339_string() to format the DateTime instance as RFC 3339 format.
  • to_rfc822_string() to format the DateTime instance as RFC 822 format.
  • to_rfc850_string() to format the DateTime instance as RFC 850 format.
import pendulum dt = pendulum.datetime(year=2021, month=1, day=1, hour=8, minute=20, second=30) print('to_date_string() result:') print(dt.to_date_string()) print('\nto_formatted_date_string() result:') print(dt.to_formatted_date_string()) print('\nto_time_string() result: ') print(dt.to_time_string()) print('\nto_datetime_string() result:') print(dt.to_datetime_string()) print('\nto_day_datetime_string() result:') print(dt.to_day_datetime_string()) print('\nto_iso8601_string() result:') print(dt.to_iso8601_string()) print('\nto_w3c_string() result:') print(dt.to_w3c_string()) print('\nto_atom_string() result:') print(dt.to_atom_string()) print('\nto_cookie_string() result:') print(dt.to_cookie_string()) print('\nto_rss_string() result: ') print(dt.to_rss_string()) print('\nto_rfc1036_string() result:') print(dt.to_rfc1036_string()) print('\nto_rfc1123_string() result:') print(dt.to_rfc1123_string()) print('\nto_rfc2822_string() result:') print(dt.to_rfc2822_string()) print('\nto_rfc3339_string() result:') print(dt.to_rfc3339_string()) print('\nto_rfc822_string() result:') print(dt.to_rfc822_string()) print('\nto_rfc850_string() result:') print(dt.to_rfc850_string())
to_date_string() result: 2021-01-01 to_formatted_date_string() result: Jan 01, 2021 to_time_string() result: 08:20:30 to_datetime_string() result: 2021-01-01 08:20:30 to_day_datetime_string() result: Fri, Jan 1, 2021 8:20 AM to_iso8601_string() result: 2021-01-01T08:20:30Z to_w3c_string() result: 2021-01-01T08:20:30+00:00 to_atom_string() result: 2021-01-01T08:20:30+00:00 to_cookie_string() result: Friday, 01-Jan-2021 08:20:30 UTC to_rss_string() result: Fri, 01 Jan 2021 08:20:30 +0000 to_rfc1036_string() result: Fri, 01 Jan 21 08:20:30 +0000 to_rfc1123_string() result: Fri, 01 Jan 2021 08:20:30 +0000 to_rfc2822_string() result: Fri, 01 Jan 2021 08:20:30 +0000 to_rfc3339_string() result: 2021-01-01T08:20:30+00:00 to_rfc822_string() result: Fri, 01 Jan 21 08:20:30 +0000 to_rfc850_string() result: Friday, 01-Jan-21 08:20:30 UTC

Format DateTime string using formatter format() and strftime() method

We also can use format() and strftime() methods to format string as below.

import pendulum dt = pendulum.datetime(year=2021, month=1, day=1, hour=8, minute=20, second=30) print(dt.format('dddd Do [of] MMMM YYYY HH:mm:ss A')) print(dt.format('YYYY-MM-DD HH:mm:ss')) print(dt.format('[Today is] dddd')) print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z')) print(dt.strftime('%I:%M:%S %p'))
Friday 1st of January 2021 08:20:30 AM 2021-01-01 08:20:30 Today is Friday 2021-01-01 08:20:30 UTC+0000 08:20:30 AM
Recommended Posts

Источник

Читайте также:  Сборщик мусора на php

How to convert pendulum to datetime.datetime type?

Nick Seong 1

The following code works for me:

In [1]: import pendulum In [2]: import datetime In [3]: pdt = pendulum.now() In [4]: datetime.datetime.fromisoformat(pdt.to_iso8601_string()) Out[4]: datetime.datetime(2022, 2, 22, 14, 29, 36, 812772,tzinfo=datetime.timezone(datetime.timedelta(seconds=28800))) 

I couldn’t find a Pendulum helper for this either. So, back to basics:

import datetime as dt tz_info = dateutil.tz.gettz(zone_name) pend_time = pendulum.datetime(. ) dt_time = dt.datetime( pend_time.year, pend_time.month, pend_time.day, pend_time.hour, pend_time.minute, pend_time.second, pend_time.microsecond, ).astimezone(tz_info) 

Note the use of dateutil. As of Python 3.6, the tzinfo documentation recommends dateutil.tz rather than pytz as an IANA time zone provider.

pendulum==1.4.0 objects have the protected _datetime member:

import pendulum p = pendulum.now() p._datetime 

This will give you something like

datetime.datetime(2021, 5, 24, 12, 44, 11, 812937, tzinfo=) 

Another way is as follows: and works for pendulum==1.4.0 and more recent pendulum==2.1.2

import pendulum from datetime import datetime p = pendulum.now() datetime_string = p.to_datetime_string() datetime.fromisoformat(datetime_string) 
datetime.datetime(2021, 5, 24, 12, 44, 11) 
>>> from datetime import datetime >>> import pendulum >>> datetime.fromtimestamp(pendulum.now().timestamp(), pendulum.tz.UTC) datetime.datetime(2021, 1, 12, 11, 41, 32, 387753, tzinfo=Timezone('UTC')) 

Usually there should be no need to do this since pendulum ‘s DateTime inherits from datetime.datetime . Any code working with stdlib’s datetime ‘s should work with pendulum’s as well.

Anthony 1779

  • How do I convert type of a datetime string which has Z in it
  • How to convert datetime in pandas to week date?
  • How to convert the datetime format to jalali date in list of dictionaries
  • How to convert string to int type (python)
  • python how to convert str «09FEB2017» to date type
  • How to convert BeautifulSoup output to a python dictionary. Also need advise on the type of database useful in managing large data in python
  • Python how to convert string with special character into datetime
  • How to convert string 2021-09-30_1 to datetime
  • How to convert generator type to string?
  • How to convert Python string type annotation to proper type?
  • How to convert JSON to an object with type information and enums?
  • How can I type convert many arguments of a function in place?
  • How to convert datetime of format YYYY-MM-DDThh:mm:ssTZD to UTC datetime?
  • How to convert in place all zoned datetime objects within a list of dicts, to UTC ISO format?
  • How to convert a datetime (‘2019-06-05T10:37:29.353+0100’) to UTC timestamp using Python3?
  • How to convert type `file` in arg parser from Python 2 to python 3?
  • How to convert a datetime to a date?
  • How to convert a really long timestamp into datetime (19 digits) (9876432101234567890)
  • How to convert string containing AM/PM to datetime in python using %p
  • How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys?
  • How to convert a python datetime to a delphi TDateTime?
  • How can I convert a timestamp string of the form «%d%H%MZ» to a datetime object?
  • How to convert a datetime.time type to float in python?
  • How to convert a UTC datetime string into date?
  • How to convert this date string into a datetime date object?
  • How to convert datetime in Pacific timezone to UTC timestamp?
  • How to convert a 2D array of seconds to a 2D array of datetime in python?
  • How to convert float64 time to datetime object
  • How to convert column type of a dataframe
  • Strptime How to convert to a datetime object
  • How would I convert this string ‘2022-07-07T10:30:00-07:00’ into datetime obj in python?
  • How to convert class type to string python SDK
  • How to convert date string with timezone to datetime in python
  • how to convert datetime object to time_ns
  • How to use min value with type datetime in Cerberus?
  • How can I extract bytes type JSON data from an API connection, and convert selected columns to a python data frame
  • How to convert string time to datetime
  • how do you convert pandas data frame epoch values to readable datetime format
  • How to convert a string to a datetime object in python?
  • How to type check a nested list of integers and convert to string?
  • How to convert between 2 type aliases in python?
  • «07:37 am GMT+5.30 on 10/11/2011» how to convert this string to datetime in python
  • How can you convert a string with varying length to datetime
  • How do I convert DataFrame column of type «string» to «float» using .replace?
  • Convert date type object to datetime
  • How to convert a str like this format ‘2020-01-01 00:00:00+00:00’ to datetime in python?
  • How to copy files of a certain type in python
  • How do I convert this into a comprehension? (Python)
  • How can you convert datetime.date from mysql into unix timestamp
  • How to convert a synchronous function to an asynchronous function in python using callbacks?

More Query from same tag

  • Add Author Username @bot.event
  • I have some image data and I am training my SVM classifier on it and I see that the support vectors are all zero. what does it mean?
  • python-xmpp and looping through list of recipients to receive and IM message
  • Remove background shading from Seaborn lineplot
  • Python 3 I’d like my exec function to resolve to a string in a list
  • Fetch argument and maintain state of argparse parser in python
  • is it possible to run compiled iron python scripts on PCs without iron python installed?
  • hit and miss transform for detecting branched point and endpoint in scikit-image
  • random output from random variable discord.py
  • how do i iterate through one dictionaries and return values from another dictionary?
  • How does the heroicons codebase make use of [xx] in a pip install heroicons[django] or heroicons[jinja]?
  • How to use «on edit» events/signals with e.g. QLineEdit in pyside6 (Qt6)
  • Reading a line in a text file, seperating numbers from words and getting the average of the the number
  • How to replace multiple items in a 2D list?
  • Scraping Tables in Python Using Beautiful Soup AttributeError: ‘NoneType’
  • Is there a better way to update Python so that it defaults to the newest version?
  • Using XArray.isel to access data in GRIB2 file from a specific location?
  • Catch universal newlines but preserve original
  • tkinter : How to create a listbox that can appear and disappear over another widget without moving the other widget?
  • extract iFrame content using BeautifulSoup
  • Use or operator in constraint cvxpy
  • Debugging Open multiprocessing.Pipe()
  • Statement in «except» tag not working in python
  • I am getting a wrong output for the Valid Palindrome Problem
  • HTTP-Post with Requests fails: BadStatusLine
  • What should be Output shape of keras model layers
  • How to make encoding consistent across the 2d array
  • Finding tables returns [] with bs4
  • Multithreading to Scrape Yahoo Finance
  • Python — Spotify API: Error 401, «no token provided»
  • pivot groupby and sum pandas dataframe
  • Trying to convert php to python and getting a syntax error
  • 24h disconnect of ISP pauses download forever
  • With imap_tools (or imaplib), how do I sync imap changes instead of polling by repeatedly fetching the entire imap database?
  • how to play songs one by one in the folder?using WMPlayer.OCX

Источник

Python parse string to DateTime with Pendulum

This Python Pendulum tutorial to show you how to use parse() and from_format() method to parse a string into DateTime instance using Pendulum package.

Table of contents

Install Pendulum package

Installing the Pendulum package using the below command.

Parse string to DateTime using parse() method

The following program we use parse() method to parse a string into DateTime instance, by default Pendulum set UTC timezone for the output DateTime instance.

import pendulum dt = pendulum.parse('2021-07-21T23:30:40') print(dt) print(dt.timezone.name)

The following Python program, we provide specific timezone during parsing the string to DateTime instance.

import pendulum dt = pendulum.parse('2021-07-21T23:30:40', tz='Asia/Tokyo') print(dt) print(dt.timezone.name)
2021-07-21T23:30:40+09:00 Asia/Tokyo

Parse string to DateTime using from_format() method

The following program we use the from_format() method to parse a string in specific format to a DateTime instance.

import pendulum dt1 = pendulum.from_format('2021-07-20 22', 'YYYY-MM-DD HH') dt2 = pendulum.from_format('2021/07/20', 'YYYY/MM/DD') print(dt1) print(dt2)
2021-07-20T22:00:00+00:00 2021-07-20T00:00:00+00:00
Recommended Posts

Источник

Оцените статью