dateutil.parser.parse remove timezone
https://stackoverflow.com/questions/27973478/how-to-remove-the-tzinfo-completely-from-the-time-after-converting-to-utc-in-pyt
How to remove the tzinfo completely from the time after converting to UTC in Python?
2017-05-23
Houman Houman
<div><div>
 
<p>I came across this exact <a href="https://stackoverflow.com/questions/12763938/why-doesnt-appengine-auto-convert-datetime-to-utc-when-calling-put">issue</a>, and I can't figure out how to achieve the solution in my case.</p>
<p>Guido says </p>
<blockquote>
 <p>The solution is to remove the tzinfo completely from the time after
 converting to UTC.</p>
</blockquote>
<p>This is what I have tried:</p>
<pre><code> date_time = parser.parse(i.pubDate.text)
 news.publication_date = date_time.replace(tzinfo=None).date()
</code></pre>
<p>And I get the same error:</p>
<pre><code>NotImplementedError: DatetimeProperty publication_date_time can only support UTC. Please derive a new Property to support alternative timezones.
</code></pre>
<p>So it seems I have to convert the date to UTC first. And here my research has failed me.</p>
<p>I came across this <a href="https://stackoverflow.com/questions/1357711/pytz-utc-conversion">solution</a>:</p>
<p>The solution suggested is this:</p>
<pre><code>def date_time_to_utc(date_time):
 tz = pytz.timezone('???')
 return tz.normalize(tz.localize(date_time)).astimezone(pytz.utc)
</code></pre>
<p>But I don't have the timezone. I am scraping the date from a html source. So the timezone could really be from anywhere in the world. Is there no easy and reliable way to convert a date time to UTC?
I could use both <code>dateutil</code> and <code>pytz</code> to achieve this. Many Thanks.</p>
<p><strong>UPDATE</strong>
It has been a really long day. I have misread the stack trace. However the question remains valid.</p>
<pre><code>date_time = (datetime}2015-01-13 18:13:26+00:00
news.publication_date_time = date_time
</code></pre>
<p>This caused the crash. And it seems by doing this, I pass the unit test:</p>
<pre><code>news.publication_date_time = date_time.replace(tzinfo=None)
</code></pre>
<p>Is this the correct way converting a GMT 0 datetime to UTC datetime? Or in fact any timezone to UTC?</p>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Collectives™ on Stack Overflow – Centralized & trusted content around the technologies you use the most.
 Learn more about Collectives
 8. Explore Collectives
 3. 
 1. Teams
 2. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 How to remove the tzinfo completely from the time after converting to UTC in Python?

 Ask Question
 Asked 8 years ago
 Modified 8 years ago
 Viewed 5k times
 Part of Google Cloud Collective
 1

 I came across this exact issue, and I can't figure out how to achieve the solution in my case.

 Guido says

 The solution is to remove the tzinfo completely from the time after converting to UTC.

 This is what I have tried:

 date_time = parser.parse(i.pubDate.text)
 news.publication_date = date_time.replace(tzinfo=None).date()
 

 And I get the same error:

 NotImplementedError: DatetimeProperty publication_date_time can only support UTC. Please derive a new Property to support alternative timezones.
 

 So it seems I have to convert the date to UTC first. And here my research has failed me.

 I came across this solution:

 The solution suggested is this:

 def date_time_to_utc(date_time):
 tz = pytz.timezone('???')
 return tz.normalize(tz.localize(date_time)).astimezone(pytz.utc)
 

 But I don't have the timezone. I am scraping the date from a html source. So the timezone could really be from anywhere in the world. Is there no easy and reliable way to convert a date time to UTC? I could use both dateutil and pytz to achieve this. Many Thanks.

 UPDATE It has been a really long day. I have misread the stack trace. However the question remains valid.

 date_time = (datetime}2015-01-13 18:13:26+00:00
 news.publication_date_time = date_time
 

 This caused the crash. And it seems by doing this, I pass the unit test:

 news.publication_date_time = date_time.replace(tzinfo=None)
 

 Is this the correct way converting a GMT 0 datetime to UTC datetime? Or in fact any timezone to UTC?

 * python
 * google-app-engine
 * datetime
 * pytz
 * python-dateutil
 Share
 Improve this question
 Follow
 edited May 23, 2017 at 12:07
 Community Bot
 1 1 1 silver badge
 asked Jan 15, 2015 at 21:40
 Houman Houman
 63.2k 86 86 gold badges 266 266 silver badges 455 455 bronze badges
 2
 * The code you've posted ("This is what I have tried:") shows you turning your 'naive' datetime into a date, but the error is coming from a DatetimeProperty. Does the trace definitely lead to the code you've shown? It looks correct...
 – Greg
 Jan 15, 2015 at 22:23
 * @Houman: you don't need .replace(tzinfo=None) before .date() . It returns a date object that is always naive.
 – jfs
 Jan 16, 2015 at 11:56
 Add a comment |

 3 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 2

 Is this the correct way converting a GMT 0 datetime to UTC datetime? Or in fact any timezone to UTC?

 If aware datetime object is already in UTC (+0000) then your formula works:

 naive_utc = aware_utc.replace(tzinfo=None)
 

 where aware_utc is a timezone-aware datetime object that represents time in UTC.

 But if aware datetime object is not in UTC; it fails. You should take into account a (possibly) non-zero UTC offset in the general case:

 assert aware.tzinfo is not None and aware.utcoffset() is not None
 # local time = utc time + utc offset (by definition)
 # -> utc = local - offset
 naive_utc = aware.replace(tzinfo=None) - aware.utcoffset()
 

 where aware is a timezone-aware datetime object in an arbitrary timezone.

 But I don't have the timezone. I am scraping the date from a html source. So the timezone could really be from anywhere in the world. Is there no easy and reliable way to convert a date time to UTC? I could use both dateutil and pytz to achieve this. Many Thanks.

 No. dateutil, pytz won't help you unless the date string itself contains the timezone (or at least its utc offset).

 Remember: It is always noon somewhere on Earth i.e., if you collect date/time strings from different places on Earth then you can't compare them unless you attach the corresponding timezones. You can't convert it to UTC, you can't get a valid POSIX timestamp if you don't know the source timezone for the date.

 Share
 Improve this answer
 Follow
 edited Jan 16, 2015 at 12:27
 answered Jan 16, 2015 at 12:02
 jfs jfs
 390k 188 188 gold badges 966 966 silver badges 1647 1647 bronze badges
 4
 * May you please explain what aware_utc means? Is GMT +1 an aware_utc ?
 – Houman
 Jan 16, 2015 at 12:12
 * @Houman: yes. no. aware_utc always has zero utc offset. GMT+1 implies 1 hour utc offset i.e., GMT+1 is not aware_utc . Just use the formula that I've provided. It always works.
 – jfs
 Jan 16, 2015 at 12:15
 * ah many thanks for the explanation. So if my datetime always shows in GMT it is safer to convert it like this: naive_utc = aware.replace(tzinfo=None) - aware.utcoffset() . Beware I live in UK, during winter time, our UTC/GMT offset is zero, hence looks the same. hence the date I provided above date_time = (datetime}2015-01-13 18:13:26+00:00 should be GMT +0, It is not UTC. (Unless I am mixing it up and the format shown is actually UTC and GMT is written differently) :)
 – Houman
 Jan 16, 2015 at 12:22
 * @Houman: yes. if the offset ever may be non-zero then you should use the more general formula.
 – jfs
 Jan 16, 2015 at 15:00
 Add a comment |
 0

 I'm an idiot and it's late here, this time I read the question.

 tstmp= date_time.replace(tzinfo=utc).total_seconds()
 naive_date = datetime.utcfromtimestamp(tstmp)
 

 First answer will just give you the current naive time

 Share
 Improve this answer
 Follow
 edited Jan 15, 2015 at 22:36
 answered Jan 15, 2015 at 22:25
 Bogdan Bogdan
 101 5 5 bronze badges
 Add a comment |
 0

 Try this:

 dateTime = dateTime.replace(tzinfo=None)
 dtUtcAware = pytz.UTC.localize(dateTime)
 
 Share
 Improve this answer
 Follow
 answered Jan 16, 2015 at 4:07
 ChrisC73 ChrisC73
 1,817 14 14 silver badges 14 14 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * google-app-engine
 * datetime
 * pytz
 * python-dateutil
 or ask your own question.

 Google Cloud Collective See more
 This question is in a collective: a subcommunity defined by tags with relevant content and experts.
 * The Overflow Blog
 * Why developer experience is the key to better software, straight from the...
 * The frontier of computing: Q&A with IBM quantum computing research
 * Featured on Meta
 * Accessibility Update: Colors
 * 2022: a year in moderation
 * Should we burninate the [balance] tag?
 * Collectives: The next iteration
 * Temporary policy: ChatGPT is banned
 Visit chat

 Linked

 47
 pytz utc conversion
 8
 Why doesn't appengine auto-convert datetime to UTC when calling put()

 Related

 2125
 How to return only the Date from a SQL Server DateTime datatype
 3682
 How do I get the current time?
 2147
 How to remove an element from a list by index
 1566
 How do I get the filename without the extension from a path in Python?
 1621
 How do I get time of a Python program's execution?
 2225
 How do I get the number of elements in a list (length of a list) in Python?
 752
 How to make a timezone aware datetime object
 1926
 How do I measure elapsed time in Python?
 368
 Converting datetime.date to UTC timestamp in Python
 2729
 How can I remove a key from a Python dictionary?

 Hot Network Questions

 * I need a seemingly large battery for project containing several sensors, what should I do?
 * In an underdetermined linear regression setup, why does the residual sum of squares equal 0?
 * A journal editor has pretended my referee report actually came from two separate referees
 * What did Paul McCartney mean by "Oh, yesterday came suddenly"?
 * Why is b.pop(0) over 200 times slower than del b[0] for bytearray?
 * What is the point of Feinting from a distance?
 * Is Metapost still relevant in the age of Lua etc.?
 * Crashing the sha1() function in PHP?
 * Can someone choose to not use their “get out of jail free” card?
 * How can an Indian homemaker spouse be guaranteed a Schengen tourist visa?
 * How to adapt a spoke salvaged from a 26" wheel to a 24" one?
 * Does the iPad Pro M2 (4th generation) support 6Ghz Wi-Fi?
 * Find the perimeter (seemingly unsolvable problem)
 * How to assign pointer to a rank 2 MTensor in Mathematica C code?
 * Are there any Oxford Colleges which will accommodate a family including children
 * Why are none of these chips identifiable?
 * How to download only certain columns of a binary file using wget?
 * quick way to add a vertex and an edge
 * Other than looking cool, what is the reason behind the TSR-2's anhedral wingtips?
 * How do I erase sets of solutions from Solve based on criteria?
 * First Age "of the Sun" terminology
 * How to decide the sequence of cheeses for a cheese tasting event?
 * Some files have '?' in the ending, need to find such files
 * Compute "negative" version of vector of vectors
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.6.43221

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Customize settings
I came across this exact issue, and I can't figure out how to achieve the solution in my case.
Guido says 
 The solution is to remove the tzinfo completely from the time after
 converting to UTC.
This is what I have tried:
  date_time = parser.parse(i.pubDate.text)
 news.publication_date = date_time.replace(tzinfo=None).date()
 
And I get the same error:
 NotImplementedError: DatetimeProperty publication_date_time can only support UTC. Please derive a new Property to support alternative timezones.
 
So it seems I have to convert the date to UTC first. And here my research has failed me.
I came across this solution:
The solution suggested is this:
 def date_time_to_utc(date_time):
 tz = pytz.timezone('???')
 return tz.normalize(tz.localize(date_time)).astimezone(pytz.utc)
 
But I don't have the timezone. I am scraping the date from a html source. So the timezone could really be from anywhere in the world. Is there no easy and reliable way to convert a date time to UTC?
I could use both dateutil and pytz to achieve this. Many Thanks.
 UPDATE
It has been a really long day. I have misread the stack trace. However the question remains valid.
 date_time = (datetime}2015-01-13 18:13:26+00:00
news.publication_date_time = date_time
 
This caused the crash. And it seems by doing this, I pass the unit test:
 news.publication_date_time = date_time.replace(tzinfo=None)
 
Is this the correct way converting a GMT 0 datetime to UTC datetime? Or in fact any timezone to UTC?
How to remove the tzinfo completely from the time after converting to UTC in Python?
https://stackoverflow.com/questions/27973478/how-to-remove-the-tzinfo-completely-from-the-time-after-converting-to-utc-in-pyt
https://www.geeksforgeeks.org/how-to-remove-timezone-information-from-datetime-object-in-python/
How to remove timezone information from DateTime object in Python
2021-09-21
Apathak
<div><article>
<div>
<p>
</p>
</div>
<div>
<p>Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.</p>
<p>In this article, we will discuss how to remove timezone information from the DateTime object.</p>
<h2>Functions Used</h2>
<ul>
<li><strong>datetime.now(tz=None): </strong>Returns the current local date and time.</li>
<li><strong>datetime.replace(): </strong>Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.</li>
</ul>
<p>To remove timestamp, tzinfo has to be set None when calling replace() function.</p>
<p>First, create a DateTime object with current time using <i><strong>datetime.now(). </strong></i>The DateTime object was then modified to contain the timezone information as well using the<i><strong> timezone.utc. </strong></i>The DateTime object with timezone information is then manipulated using the<i><strong> .replace()</strong></i> method to remove the timezone information using the <i><strong>tzinfo </strong></i>parameter.</p>
<p><strong>Syntax:</strong></p>
<blockquote>
<p>replace(tzinfo=None)</p>
</blockquote>
<p><strong>Example:</strong></p>
<div>
<h2>Python</h2>
<div>
<p><code>from</code> <code>datetime </code><code>import</code> <code>datetime, timezone</code></p>
<p><code>dt_obj_w_tz </code><code>=</code> <code>datetime.now()</code></p>
<p><code>print</code><code>(dt_obj_w_tz)</code></p>
<p><code>dt_obj_w_tz </code><code>=</code> <code>dt_obj_w_tz.replace(tzinfo</code><code>=</code><code>timezone.utc)</code></p>
<p><code>print</code><code>(dt_obj_w_tz)</code></p>
<p><code>dt_obj_wo_tz </code><code>=</code> <code>dt_obj_w_tz.replace(tzinfo</code><code>=</code><code>None</code><code>)</code></p>
<p><code>print</code><code>(dt_obj_wo_tz)</code></p>
</div></div>
<p><strong>Output:</strong> </p>
<pre>2021-08-10 12:51:42.093388
2021-08-10 12:51:42.093388+00:00
2021-08-10 12:51:42.09338</pre>
<p>However, the datetime object with timestamp can be created by providing <i><strong>tz</strong></i> parameter.</p>
<p><strong>Example:</strong></p>
<div>
<h2>Python</h2>
<div>
<p><code>from</code> <code>datetime </code><code>import</code> <code>datetime, timezone</code></p>
<p><code>dt_obj_w_tz </code><code>=</code> <code>datetime.now(tz</code><code>=</code><code>timezone.utc)</code></p>
<p><code>print</code><code>(dt_obj_w_tz)</code></p>
<p><code>dt_obj_wo_tz </code><code>=</code> <code>dt_obj_w_tz.replace(tzinfo</code><code>=</code><code>None</code><code>)</code></p>
<p><code>print</code><code>(dt_obj_wo_tz)</code></p>
</div></div>
<p><strong>Output:</strong></p>
<pre>2021-08-10 07:21:57.838856+00:00
2021-08-10 07:21:57.838856</pre>
<br/> <br/>
<div>
<p>
</p>
</div> <div> <p> <h3>Please <u></u> to comment...</h3></p>
</div>
</div>
</article></div>||||I|||| Skip to content
 * Tutorials
 + Python Tutorial
 o Taking Input in Python
 o Python Operators
 o Python Data Types
 - Python Numbers
 - Python String
 - Python Lists
 - Python Tuples
 - Sets in Python
 - Python Dictionary
 o Python Loops and Control Flow
 - Python If Else
 - Python For Loops
 - Python While Loops
 - Python Breaks
 - Python Continue Statement
 - Python Pass Statement
 o Python Functions
 o Python OOPS Concept
 o Python Data Structures
 - Python DSA
 - Linked List
 - Stack
 - Queue
 - Tree
 - Heap
 - Hashing
 - Graph
 - Sets
 - Map
 - Advance Data Structure
 - Sorting Algorithms
 - Searching Algorithms
 o Python Exception Handling
 o Python File Handling
 o Python Exercises
 - Python List Exercise
 - Python String Exercise
 - Python Tuple Exercise
 - Python Dictionary Exercise
 - Python Set Exercise
 - Python Design Patterns
 - Python Programming Examples
 - Python Practice Questions
 + Java
 o Java Programming Language
 - Java Tutorial
 - Data Types
 - Variables
 - Operators
 * Operators in Java
 * Arithmetic Operators
 * Unary Operators
 * Assignment Operators
 * Relational Operators
 * Logical Operators
 * Ternary Operators
 - Flow Control in Java
 * Flow Control
 * if Statement
 * if-else Statement
 * if-else-if Ladder
 * Continue Statement
 * Break Statement
 * Return Statement
 - Loops in Java
 * Loops
 * do-while Loop
 * For Loop
 * For-each Loop
 - Methods
 - Strings
 - Arrays
 - OOPs Concepts
 * OOPs Concepts
 * Classes and Objects
 * Access Modifiers
 * Inheritance
 * Abstraction
 * Encapsulation
 * Polymorphism
 - Interface
 - Packages
 - Multithreading
 - File Handling
 - Regular Expression
 o Java Collections
 - Java Collections
 - Collection Class
 - List Interface
 - ArrayList
 - Vector Class
 - Stack Class
 - LinkedList Class
 - Queue Interface
 - Set Interface
 - HashSet Class
 - TreeSet
 - Map Interface
 - HashMap Class
 - HashTable Class
 - Iterator
 - Comparator
 - Collection Interview Questions
 o Java 8 Tutorial
 o Java Programs
 - Java Programming Examples
 - Java Array Programs
 - Java String Programs
 - Java Date-Time Programs
 - Java File Handling Programs
 - Java Collection Programs
 - Java JDBC Programs
 - Java Apache POI Programs
 - Java OpenCV Programs
 o Java Interview Questions
 - Java Interview Questions
 - Core Java Interview Questions-Freshers
 - Java Multithreading Interview Questions
 - OOPs Interview Questions and Answers
 o Java Exercises
 o Java Quiz
 - Java Quiz
 - Core Java MCQ
 o Java Projects
 o Advance Java
 - Spring Tutorial
 - Spring Boot Tutorial
 - Spring Boot Interview Questions
 - Spring MVC Tutorial
 - Spring MVC Interview Questions
 - Hibernate Tutorial
 - Hibernate Interview Questions
 + Programming Languages
 o C
 o C++
 o JavaScript
 o PHP
 o R Tutorial
 o C#
 o SQL
 o Scala
 o Perl
 o Go Language
 o Kotlin
 + System Design
 o System Design Tutorial
 - What is System Design
 - Key Terminologies in System Design
 - Analysis and Architecture of Systems
 - Scalability in System Design
 - Databases in System Design
 - High Level Design or HLD
 - Low Level Design or LLD
 - Communication Protocols
 - Web Servers and Proxies
 - Case Studies in Designing Systems
 - Complete System Design Tutorial
 o Software Design Patterns
 - Factory Pattern
 - Observer Pattern
 - Singleton Design Pattern
 - Decorator Pattern
 - Strategy Pattern
 - Adapter Pattern
 - Command Pattern
 - Iterator Pattern
 - Prototype Design Pattern
 - All Design Patterns
 o System Design Roadmap
 o Top 10 System Design Interview Questions and Answers
 + Interview Corner
 o Company Preparation
 o Top Topics
 o Practice Company Questions
 o Interview Experiences
 o Experienced Interviews
 o Internship Interviews
 o Competitive Programming
 o Multiple Choice Quizzes
 o Aptitude for Placements
 + Computer Science Subjects
 o Mathematics
 o Operating System
 o DBMS
 o Computer Networks
 o Computer Organization and Architecture
 o Theory of Computation
 o Compiler Design
 o Digital Logic
 o Software Engineering
 + DevOps
 o GIT
 o AWS
 o Docker
 o Kubernetes
 o Microsoft Azure Tutorial
 o Google Cloud Platform
 + Linux
 o Linux Tutorial
 o Linux Commands A-Z
 o Linux Commands Cheatsheet
 o 25 Basic Linux Commands
 o File Mangement in Linux
 o File Permission Commands
 - chmod Command
 - chown Command
 - chgrp Command
 - unmask Command
 o Linux System Administration
 o Linux File System
 o Linux Shell Scripting
 o Linux Networking
 o Linux Firewall
 o Linux Interview Questions
 + Software Testing
 o Software Testing Tutorial
 - Software Testing Tutorial
 - What is Software Testing
 - Principles of Software Testing
 - Types of Software Testing
 - Levels of Software Testing
 - Automation Testing
 - Manual Testing
 o Testing Tools
 - Software Testing Tools
 - Defect Testing Tools
 - Cross-Browser Testing Tools
 - Integration Testing Tool
 - Unit Testing Tools
 - Mobile Testing Tools
 - GUI Testing Tool
 - Security Testing Tools
 - Penetration Testing Tools
 o Selenium
 - Selenium Tutorial
 - Selenium Basics
 - Selenium Python
 o Jira
 - Jira Tutorial
 - JIRA Installation
 - JIRA Login
 - JIRA Dashboard
 o Software Engineering
 - Software Engineering Tutorial
 - Software Development Life Cycle (SDLC)
 - Software Characteristics
 - Software Quality
 - Waterfall Model
 - Iterative Waterfall Model
 - Spiral Model
 - Prototyping Model
 - Incremental Process Model
 o Interview Questions
 - Software Testing Interview Questions
 - Automation Testing Interview Questions
 - Manual Testing Interview Questions
 - Software Engineering Interview Questions
 - Penetration Testing Interview Questions
 - API Testing Interview Questions
 o Postman
 - Postman Tutorial
 - Postman for API Development
 - Download and Install Postman
 - API Testing Using Postman
 - Generate HTML Report for Postman
 + Databases
 o DBMS Tutorial
 o SQL Tutorial
 o PostgreSQL Tutorial
 o MongoDB Tutorial
 o SQL Interview Questions
 o MySQL Interview Questions
 o PL/SQL Interview Questions
 + Android
 o Android Tutorial
 o Android Studio Tutorial
 o Kotlin For Android
 o Android Projects
 o Android Interview Questions
 o 6 Weeks of Android App Development
 + Excel
 o MS Excel Tutorial
 o Introduction to MS Excel
 o Data Analysis in Excel
 o Basic Excel Formulas & Functions
 o Data Analysis in Advanced Excel
 o Workbooks
 o Statistical Functions
 o Data Visualization in Excel
 o Pivot Tables in Excel
 o Excel Spreadsheets in Python
 o Basic Excel Shortcuts
 + Mathematics
 o Number System
 o Algebra
 o Linear Algebra
 o Trigonometry
 o Set Theory
 o Statistics
 o Probability
 o Geometry
 o Mensuration
 o Logarithms
 o Calculus
 + Commerce
 o Business Studies
 o Accountancy
 o Microeconomics
 o Statistics for Economics
 o Macroeconomics
 o Human Resource Management (HRM)
 o Management
 o Income Tax
 o Finance
 o Commerce Complete Guide
 + SEO-Search Engine Optimization
 o What is SEO
 o Search Engine Optimization Basics
 o Types of SEO
 o Keyword Optimization in SEO
 o Backlinks in SEO
 o SEO Blogs
 o Mobile SEO
 o SEO Complete Reference
 + Aptitude
 o Aptitude Question and Answers
 o Quantitative Aptitude
 o Logical Reasoning
 o Verbal Ability
 * DSA
 + Data Structures
 o Arrays
 o Matrix
 o Strings
 o Linked List
 - Singly Linked List
 - Doubly Linked List
 - Circular Linked List
 - Doubly Circular Linked List
 - Linked List Tutorial
 o Stack
 o Queue
 o Tree
 - Generic Tree
 - Binary Tree
 - Binary Search Tree
 - AVL Tree
 - B Tree
 - B+ Tree
 - Red Black Tree
 - Tree Data Structure Tutorial
 o Heap
 o Hashing
 o Graph
 o Set Data Structure
 o Map Data Structure
 o Advanced Data Structure
 o Data Structures Tutorial
 + Algorithms
 o Analysis of Algorithms
 - Design and Analysis of Algorithms
 - Asymptotic Analysis
 - Asymptotic Notations
 - Worst, Average and Best Cases
 o Searching Algorithms
 - Linear Search
 - Binary Search
 - Searching Algorithms Tutorial
 o Sorting Algorithms
 - Selection Sort
 - Bubble Sort
 - Insertion Sort
 - Merge Sort
 - Quick Sort
 - Heap Sort
 - Counting Sort
 - Radix Sort
 - Bucket Sort
 - Sorting Algorithms Tutorial
 o Greedy Algorithms
 o Dynamic Programming
 o Graph Algorithms
 o Pattern Searching
 o Recursion
 o Backtracking
 o Divide and Conquer
 o Mathematical Algorithms
 o Geometric Algorithms
 o Bitwise Algorithms
 o Randomized Algorithms
 o Branch and Bound
 o Algorithms Tutorial
 + DSA Tutorial
 + Practice
 o All DSA Problems
 o Problem of the Day
 o Company Wise Coding Practice
 - Amazon
 - Microsoft
 - Flipkart
 - Explore All
 o GfG SDE Sheet
 o Practice Problems Difficulty Wise
 - School
 - Basic
 - Easy
 - Medium
 - Hard
 o Language Wise Coding Practice
 - CPP
 - Java
 - Python
 o Curated DSA Lists
 - Beginner's DSA Sheet
 - Top 50 Array Problems
 - Top 50 String Problems
 - Top 50 DP Problems
 - Top 50 Graph Problems
 - Top 50 Tree Problems
 + Competitive Programming
 + Company Wise SDE Sheets
 o Facebook SDE Sheet
 o Amazon SDE Sheet
 o Apple SDE Sheet
 o Netflix SDE Sheet
 o Google SDE Sheet
 + DSA Cheat Sheets
 o SDE Sheet
 o DSA Sheet for Beginners
 o FAANG Coding Sheet
 o Product-Based Coding Sheet
 o Company-Wise Preparation Sheet
 + Top Interview Questions
 o Top 100 DSA Interview Questions Topic-wise
 + Puzzles
 o All Puzzles
 o Top 100 Puzzles Asked In Interviews
 o Top 20 Puzzles Commonly Asked During SDE Interviews
 * Data Science
 + Python Tutorial
 + R Tutorial
 + Machine Learning
 + Data Science using Python
 + Data Science using R
 + Data Science Packages
 o Pandas Tutorial
 o NumPy Tutorial
 + Data Visualization
 o Python Data Visualization Tutorial
 o Data Visualization with R
 + Data Analysis
 o Data Analysis with Python
 o Data Analysis with R
 + Deep Learning
 + NLP Tutorial
 * Web Tech
 + HTML Tutorial
 + CSS Tutorial
 + JavaScript Tutorial
 + PHP Tutorial
 + ReactJS Tutorial
 + NodeJS Tutorial
 + AngularJS Tutorial
 + Bootstrap Tutorial
 + Web Development Using Python
 o Django
 - Getting started with Django
 - Create an App in Django
 - Views In Django
 - Django Templates
 - Django URL patterns
 - Django Admin Interface
 - Django Models
 - MySQL Databased with Django
 - Django CRUD
 - Django Forms
 - Django Static File
 - Projects for Beginners
 - Django Tutorial
 o Flask
 - Web Development Using Flask
 - Flask App Routing
 - URL building in Flask
 - Flask Templates
 - Templating With Jinja2 in Flask
 - Flask Model
 - Database with Flask SQL Alchemy
 - Authentication with Flask
 - WTForms in Flask
 - Static files in Flask
 - Python Flask Projects
 - Flask Interview Questions
 o Frontend Projects
 - Building a Survey Form using HTML and CSS
 - Food delivery system using HTML and CSS
 - ToDo webapp using Django
 - Building Blog CMS
 - Add Pagination in Django
 - Tailwind CSS with Django
 - Django with Reactjs
 o Postman
 o Github
 + JSON Tutorial
 + TypeScript Tutorial
 + Wordpress Tutorial
 + Web Design
 + Web Browsers
 o Google Chrome
 o Mozilla Firefox
 o Apple Safari
 o Microsoft Edge
 o Tor
 + Cheat Sheets
 o HTML Cheat Sheet
 o CSS Cheat Sheet
 o JavaScript Cheat Sheet
 o React Cheat Sheet
 o Angular Cheat Sheet
 o jQuery Cheat Sheet
 o Bootstrap Cheat Sheet
 + JavaScript Projects
 + Learn Complete Web Development
 + File Formats
 * Courses
 + Coding for Everyone
 + DSA to Development
 + Machine Learning and Data Science
 + DSA Courses
 o Data Structure & Algorithm(C++/JAVA)
 o Data Structure & Algorithm(Python)
 o Data Structure & Algorithm(JavaScript)
 + Programming Languages
 o CPP
 o Java
 o Python
 o JavaScript
 o C
 * 
 * 
 * 
 * 
 + 
 + Python Basics
 + Interview Questions
 + Python Quiz
 + Popular Packages
 + Python Projects
 + Practice Python
 + AI With Python
 + Learn Python3
 + Python Automation
 + Python Web Dev
 + DSA with Python
 + Python OOPs
 + Lists
 + Strings
 + Dictionaries
 ▲
 Open In App
 + How to remove timezone information from DateTime object in Python
 + How to make a timezone aware datetime object in Python
 + How to convert Python's .isoformat() string back into datetime object
 + How to add time onto a DateTime object in Python
 + How to convert timestamp string to datetime object in Python?
 + Working with Datetime Objects and Timezones in Python
 + Add Months to datetime Object in Python
 + Convert "unknown format" strings to datetime objects in Python
 + How to change the Pandas datetime format in Python?
 + How to Fix - "datetime.datetime not JSON serializable" in Python?
 + How to Remove Time from Date/Timestamp in Excel?
 + How to remove timezone from a Timestamp column in a Pandas Dataframe
 + Python | datetime.timedelta() function
 + Python DateTime - time.replace() Method with Example
 + How to get the client timezone offset in JavaScript?
 + Convert Datetime Object To Local Time Zone In Pandas
 + How to convert date and time with different timezones in Python?
 + Get Time Zone of a Given Location using Python
 + Convert string to datetime in Python with timezone
 + Isoformat to datetime - Python
 + Add Years to datetime Object in Python
 + Manipulate Date and Time with the Datetime Module in Python
 + Isoformat() Method Of Datetime Class In Python
 + Extract time from datetime in Python
 + Datetime.replace() Function in Python
 + Pandas Series dt.to_pydatetime | Return Python DateTime Objects
 + Python datetime.timetz() Method with Example
 + Ruby | DateTime to_time() function
 + PHP | date_timezone_get() Function
 + Ruby | Time to_datetime() function

 How to remove timezone information from DateTime object in Python

 Last Updated : 09 Dec, 2021
 Improve


 + 
 + 
 + 
 Improve
 Like Article
 Like
 Save
 Share
 Report

 Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.

 In this article, we will discuss how to remove timezone information from the DateTime object.

 Functions Used

 + datetime.now(tz=None): Returns the current local date and time.
 + datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.

 To remove timestamp, tzinfo has to be set None when calling replace() function.

 First, create a DateTime object with current time using datetime.now(). The DateTime object was then modified to contain the timezone information as well using the timezone.utc. The DateTime object with timezone information is then manipulated using the .replace() method to remove the timezone information using the tzinfo parameter.

 Syntax:

 replace(tzinfo=None)

 Example:

 Python




 from datetime import datetime, timezone 
 # Get the datetime object using datetime 
 # module 
 dt_obj_w_tz = datetime.now() 
 print(dt_obj_w_tz) 
 # Add timezone information to the datetime 
 # object 
 dt_obj_w_tz = dt_obj_w_tz.replace(tzinfo=timezone.utc)
 print(dt_obj_w_tz) 
 # Remove the timezone information from the datetime 
 # object 
 dt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None) 
 print(dt_obj_wo_tz) 
 

 Output:

 2021-08-10 12:51:42.093388
 2021-08-10 12:51:42.093388+00:00
 2021-08-10 12:51:42.09338

 However, the datetime object with timestamp can be created by providing tz parameter.

 Example:

 Python




 from datetime import datetime, timezone 
 # Get the datetime object with timezone 
 # information 
 dt_obj_w_tz = datetime.now(tz=timezone.utc) 
 print(dt_obj_w_tz) 
 # Remove the timezone information from the 
 # datetime object 
 dt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)
 print(dt_obj_wo_tz) 
 

 Output:

 2021-08-10 07:21:57.838856+00:00
 2021-08-10 07:21:57.838856


 Like Article

 Suggest improvement


 Next
 How to make a timezone aware datetime object in Python
 Share your thoughts in the comments
 Add Your Comment

 Please Login to comment...

 Similar Reads

 How to make a timezone aware datetime object in Python
 Convert string to datetime in Python with timezone
 DateTime Timezone in SQLAlchemy
 Pandas Series dt.tz_convert | Change Timezone in DateTime Series
 Python DateTime - DateTime Class
 How to convert a Python datetime.datetime to excel serial date number
 How to Fix - "datetime.datetime not JSON serializable" in Python?
 How to remove timezone from a Timestamp column in a Pandas Dataframe
 Python | Timezone Conversion
 Get Current Time in different Timezone using Python
 apathak092
 Follow




 Article Tags :
 + Python-datetime
 + Python




 Practice Tags :
 + python




 A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh - 201305
 + Company
 + About Us
 + Legal
 + Careers
 + In Media
 + Contact Us
 + Advertise with us
 + GFG Corporate Solution
 + Placement Training Program
 + Explore
 + Hack-A-Thons
 + GfG Weekly Contest
 + DSA in JAVA/C++
 + Master System Design
 + Master CP
 + GeeksforGeeks Videos
 + Geeks Community
 + Languages
 + Python
 + Java
 + C++
 + PHP
 + GoLang
 + SQL
 + R Language
 + Android Tutorial
 + Tutorials Archive
 + DSA
 + Data Structures
 + Algorithms
 + DSA for Beginners
 + Basic DSA Problems
 + DSA Roadmap
 + Top 100 DSA Interview Problems
 + DSA Roadmap by Sandeep Jain
 + All Cheat Sheets
 + Data Science & ML
 + Data Science With Python
 + Data Science For Beginner
 + Machine Learning Tutorial
 + ML Maths
 + Data Visualisation Tutorial
 + Pandas Tutorial
 + NumPy Tutorial
 + NLP Tutorial
 + Deep Learning Tutorial
 + HTML & CSS
 + HTML
 + CSS
 + Web Templates
 + CSS Frameworks
 + Bootstrap
 + Tailwind CSS
 + SASS
 + LESS
 + Web Design
 + Django Tutorial
 + Python Tutorial
 + Python Programming Examples
 + Python Projects
 + Python Tkinter
 + Web Scraping
 + OpenCV Tutorial
 + Python Interview Question
 + Computer Science
 + Operating Systems
 + Computer Network
 + Database Management System
 + Software Engineering
 + Digital Logic Design
 + Engineering Maths
 + DevOps
 + Git
 + AWS
 + Docker
 + Kubernetes
 + Azure
 + GCP
 + DevOps Roadmap
 + Competitive Programming
 + Top DS or Algo for CP
 + Top 50 Tree
 + Top 50 Graph
 + Top 50 Array
 + Top 50 String
 + Top 50 DP
 + Top 15 Websites for CP
 + System Design
 + High Level Design
 + Low Level Design
 + UML Diagrams
 + Interview Guide
 + Design Patterns
 + OOAD
 + System Design Bootcamp
 + Interview Questions
 + JavaScript
 + JavaScript Examples
 + TypeScript
 + ReactJS
 + NextJS
 + AngularJS
 + NodeJS
 + Lodash
 + Web Browser
 + Preparation Corner
 + Company-Wise Recruitment Process
 + Resume Templates
 + Aptitude Preparation
 + Puzzles
 + Company-Wise Preparation
 + School Subjects
 + Mathematics
 + Physics
 + Chemistry
 + Biology
 + Social Science
 + English Grammar
 + World GK
 + Management & Finance
 + Management
 + HR Management
 + Finance
 + Income Tax
 + Organisational Behaviour
 + Marketing
 + Free Online Tools
 + Typing Test
 + Image Editor
 + Code Formatters
 + Code Converters
 + Currency Converter
 + Random Number Generator
 + Random Password Generator
 + More Tutorials
 + Software Development
 + Software Testing
 + Product Management
 + SAP
 + SEO - Search Engine Optimization
 + Linux
 + Excel
 + GeeksforGeeks Videos
 + DSA
 + Python
 + Java
 + C++
 + Data Science
 + CS Subjects
 @GeeksforGeeks, Sanchhaya Education Private Limited , All rights reserved
 We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !

 What kind of Experience do you want to share?

 Interview Experiences
 Admission Experiences
 Career Compass for School Students
 Work Experiences
 Campus Experiences
 Competitive Exam Experiences
 Can't choose a topic to write? click here for suggested topics
 Write and publish your own Article
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.
In this article, we will discuss how to remove timezone information from the DateTime object.
Functions Used
 datetime.now(tz=None): Returns the current local date and time.
 datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.
To remove timestamp, tzinfo has to be set None when calling replace() function.
First, create a DateTime object with current time using  datetime.now().  The DateTime object was then modified to contain the timezone information as well using the  timezone.utc.  The DateTime object with timezone information is then manipulated using the  .replace()  method to remove the timezone information using the  tzinfo  parameter.
 Syntax: 
replace(tzinfo=None)
 Example: 
Python
 from datetime  import datetime, timezone 
 dt_obj_w_tz  = datetime.now() 
 print (dt_obj_w_tz) 
 dt_obj_w_tz  = dt_obj_w_tz.replace(tzinfo = timezone.utc) 
 print (dt_obj_w_tz) 
 dt_obj_wo_tz  = dt_obj_w_tz.replace(tzinfo = None ) 
 print (dt_obj_wo_tz) 
 
 Output: 
2021-08-10 12:51:42.093388
2021-08-10 12:51:42.093388+00:00
2021-08-10 12:51:42.09338
However, the datetime object with timestamp can be created by providing  tz  parameter.
 Example: 
Python
 from datetime  import datetime, timezone 
 dt_obj_w_tz  = datetime.now(tz = timezone.utc) 
 print (dt_obj_w_tz) 
 dt_obj_wo_tz  = dt_obj_w_tz.replace(tzinfo = None ) 
 print (dt_obj_wo_tz) 
 
 Output: 
2021-08-10 07:21:57.838856+00:00
2021-08-10 07:21:57.838856
 
   Please   to comment...
How to remove timezone information from DateTime object in Python
https://www.geeksforgeeks.org/how-to-remove-timezone-information-from-datetime-object-in-python/
https://dateutil.readthedocs.io/en/stable/parser.html
parserÂ¶
2021-07-13
None
<div><div>
 
 <nav>
 
 </nav>
 <section>
 
 <nav>
 
 <i></i>
 <a href="index.html">dateutil</a>
 
 </nav>
 <div>
<p>This module offers a generic date/time string parser which is able to parse
most known formats to represent a date and/or time.</p>
<p>This module attempts to be forgiving with regards to unlikely input formats,
returning a datetime object even for dates which are ambiguous. If an element
of a date/time stamp is omitted, the following rules are applied:</p>
<ul>
<li>If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour
on a 12-hour clock (<code>0 &lt;= hour &lt;= 12</code>) <em>must</em> be specified if AM or PM is
specified.</li>
<li>If a time zone is omitted, a timezone-naive datetime is returned.</li>
</ul>
<p>If any other elements are missing, they are taken from the
<code>datetime.datetime</code> object passed to the parameter <code>default</code>. If this
results in a day number exceeding the valid number of days per month, the
value falls back to the end of the month.</p>
<p>Additional resources about date/time string formats can be found below:</p>
<ul>
<li><a href="https://www.cl.cam.ac.uk/~mgk25/iso-time.html">A summary of the international standard date and time notation</a></li>
<li><a href="https://www.w3.org/TR/NOTE-datetime">W3C Date and Time Formats</a></li>
<li><a href="https://pds-rings.seti.org/tools/time_formats.html">Time Formats (Planetary Rings Node)</a></li>
<li><a href="https://metacpan.org/pod/release/MUIR/Time-modules-2013.0912/lib/Time/ParseDate.pm">CPAN ParseDate module</a></li>
<li><a href="https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html">Java SimpleDateFormat Class</a></li>
</ul>
<div>
<h2>Functions<a href="#functions">Â¶</a></h2>
<dl>
<dt>
<code>parser.</code><code>parse</code>(<em>parserinfo=None</em>, <em>**kwargs</em>)<a href="_modules/dateutil/parser/_parser.html#parser.parse">[source]</a><a href="#dateutil.parser.parse">Â¶</a></dt>
<dd><p>Parse a string in one of the supported formats, using the
<code>parserinfo</code> parameters.</p>
<table>
<colgroup><col></col>
<col></col>
</colgroup><tbody>
<tr><th>Parameters:</th><td><ul>
<li><strong>timestr</strong> â A string containing a date/time stamp.</li>
<li><strong>parserinfo</strong> â A <a href="#dateutil.parser.parserinfo"><code>parserinfo</code></a> object containing parameters for the parser.
If <code>None</code>, the default arguments to the <a href="#dateutil.parser.parserinfo"><code>parserinfo</code></a>
constructor are used.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>The <code>**kwargs</code> parameter takes the following keyword arguments:</p>
<table>
<colgroup><col></col>
<col></col>
</colgroup><tbody>
<tr><th>Parameters:</th><td><ul>
<li><strong>default</strong> â The default datetime object, if this is a datetime object and not
<code>None</code>, elements specified in <code>timestr</code> replace elements in the
default object.</li>
<li><strong>ignoretz</strong> â If set <code>True</code>, time zones in parsed strings are ignored and a naive
<code>datetime</code> object is returned.</li>
<li><strong>tzinfos</strong> â <p>Additional time zone names / aliases which may be present in the
string. This argument maps time zone names (and optionally offsets
from those time zones) to time zones. This parameter can be a
dictionary with timezone aliases mapping time zone names to time
zones or a function taking two parameters (<code>tzname</code> and
<code>tzoffset</code>) and returning a time zone.</p>
<p>The timezones to which the names are mapped can be an integer
offset from UTC in seconds or a <code>tzinfo</code> object.</p>
<div><pre> &gt;&gt;&gt; from dateutil.parser import parse
 &gt;&gt;&gt; from dateutil.tz import gettz
 &gt;&gt;&gt; tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
 &gt;&gt;&gt; parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
 datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
 &gt;&gt;&gt; parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
 datetime.datetime(2012, 1, 19, 17, 21,
 tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
</pre></div>
<p>This parameter is ignored if <code>ignoretz</code> is set.</p>
</li>
<li><strong>dayfirst</strong> â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (<code>True</code>) or month (<code>False</code>). If
<code>yearfirst</code> is set to <code>True</code>, this distinguishes between YDM and
YMD. If set to <code>None</code>, this value is retrieved from the current
<a href="#dateutil.parser.parserinfo"><code>parserinfo</code></a> object (which itself defaults to <code>False</code>).</li>
<li><strong>yearfirst</strong> â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the year. If <code>True</code>, the first number is taken to
be the year, otherwise the last number is taken to be the year. If
this is set to <code>None</code>, the value is retrieved from the current
<a href="#dateutil.parser.parserinfo"><code>parserinfo</code></a> object (which itself defaults to <code>False</code>).</li>
<li><strong>fuzzy</strong> â Whether to allow fuzzy parsing, allowing for string like âToday is
January 1, 2047 at 8:21:00AMâ.</li>
<li><strong>fuzzy_with_tokens</strong> â <p>If <code>True</code>, <code>fuzzy</code> is automatically set to True, and the parser
will return a tuple where the first element is the parsed
<code>datetime.datetime</code> datetimestamp and the second element is
a tuple containing the portions of the string which were ignored:</p>
<div><pre>&gt;&gt;&gt; from dateutil.parser import parse
&gt;&gt;&gt; parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
(datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
</pre></div>
</li>
</ul>
</td>
</tr>
<tr><th>Returns:</th><td><p>Returns a <code>datetime.datetime</code> object or, if the
<code>fuzzy_with_tokens</code> option is <code>True</code>, returns a tuple, the
first element being a <code>datetime.datetime</code> object, the second
a tuple containing the fuzzy tokens.</p>
</td>
</tr>
<tr><th>Raises:</th><td><ul>
<li><a href="#dateutil.parser.ParserError"><strong>ParserError</strong></a> â Raised for invalid or unknown string formats, if the provided
<code>tzinfo</code> is not in a valid format, or if an invalid date would
be created.</li>
<li><strong>OverflowError</strong> â Raised if the parsed date exceeds the largest valid C integer on
your system.</li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd></dl>
<dl>
<dt>
<em>classmethod </em><code>parser.</code><code>isoparse</code>(<em>dt_str</em>)<a href="#dateutil.parser.isoparse">Â¶</a></dt>
<dd><p>Parse an ISO-8601 datetime string into a <code>datetime.datetime</code>.</p>
<p>An ISO-8601 datetime string consists of a date portion, followed
optionally by a time portion - the date and time portions are separated
by a single character separator, which is <code>T</code> in the official
standard. Incomplete date formats (such as <code>YYYY-MM</code>) may <em>not</em> be
combined with a time portion.</p>
<p>Supported date formats are:</p>
<p>Common:</p>
<ul>
<li><code>YYYY</code></li>
<li><code>YYYY-MM</code> or <code>YYYYMM</code></li>
<li><code>YYYY-MM-DD</code> or <code>YYYYMMDD</code></li>
</ul>
<p>Uncommon:</p>
<ul>
<li><code>YYYY-Www</code> or <code>YYYYWww</code> - ISO week (day defaults to 0)</li>
<li><code>YYYY-Www-D</code> or <code>YYYYWwwD</code> - ISO week and day</li>
</ul>
<p>The ISO week and day numbering follows the same logic as
<code>datetime.date.isocalendar()</code>.</p>
<p>Supported time formats are:</p>
<ul>
<li><code>hh</code></li>
<li><code>hh:mm</code> or <code>hhmm</code></li>
<li><code>hh:mm:ss</code> or <code>hhmmss</code></li>
<li><code>hh:mm:ss.ssssss</code> (Up to 6 sub-second digits)</li>
</ul>
<p>Midnight is a special case for <cite>hh</cite>, as the standard supports both
00:00 and 24:00 as a representation. The decimal separator can be
either a dot or a comma.</p>
<div>
<p>Caution</p>
<p>Support for fractional components other than seconds is part of the
ISO-8601 standard, but is not currently implemented in this parser.</p>
</div>
<p>Supported time zone offset formats are:</p>
<ul>
<li><cite>Z</cite> (UTC)</li>
<li><cite>Â±HH:MM</cite></li>
<li><cite>Â±HHMM</cite></li>
<li><cite>Â±HH</cite></li>
</ul>
<p>Offsets will be represented as <a href="tz.html#dateutil.tz.tzoffset"><code>dateutil.tz.tzoffset</code></a> objects,
with the exception of UTC, which will be represented as
<a href="tz.html#dateutil.tz.tzutc"><code>dateutil.tz.tzutc</code></a>. Time zone offsets equivalent to UTC (such
as <cite>+00:00</cite>) will also be represented as <a href="tz.html#dateutil.tz.tzutc"><code>dateutil.tz.tzutc</code></a>.</p>
<table>
<colgroup><col></col>
<col></col>
</colgroup><tbody>
<tr><th>Parameters:</th><td><strong>dt_str</strong> â A string or stream containing only an ISO-8601 datetime string</td>
</tr>
<tr><th>Returns:</th><td>Returns a <code>datetime.datetime</code> representing the string.
Unspecified components default to their lowest value.</td>
</tr>
</tbody>
</table>
<div>
<p>Warning</p>
<p>As of version 2.7.0, the strictness of the parser should not be
considered a stable part of the contract. Any valid ISO-8601 string
that parses correctly with the default settings will continue to
parse correctly in future versions, but invalid strings that
currently fail (e.g. <code>2017-01-01T00:00+00:00:00</code>) are not
guaranteed to continue failing in future versions if they encode
a valid date.</p>
</div>
<p>New in version 2.7.0.</p>
</dd></dl>
</div>
<div>
<h2>Classes<a href="#classes">Â¶</a></h2>
<dl>
<dt>
<em>class </em><code>dateutil.parser.</code><code>parserinfo</code>(<em>dayfirst=False</em>, <em>yearfirst=False</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo">[source]</a><a href="#dateutil.parser.parserinfo">Â¶</a></dt>
<dd><p>Class which handles what inputs are accepted. Subclass this to customize
the language and acceptable values for each parameter.</p>
<table>
<colgroup><col></col>
<col></col>
</colgroup><tbody>
<tr><th>Parameters:</th><td><ul>
<li><strong>dayfirst</strong> â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (<code>True</code>) or month (<code>False</code>). If
<code>yearfirst</code> is set to <code>True</code>, this distinguishes between YDM
and YMD. Default is <code>False</code>.</li>
<li><strong>yearfirst</strong> â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the year. If <code>True</code>, the first number is taken
to be the year, otherwise the last number is taken to be the year.
Default is <code>False</code>.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<dl>
<dt>
<code>AMPM</code><em> = [('am', 'a'), ('pm', 'p')]</em><a href="#dateutil.parser.parserinfo.AMPM">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>HMS</code><em> = [('h', 'hour', 'hours'), ('m', 'minute', 'minutes'), ('s', 'second', 'seconds')]</em><a href="#dateutil.parser.parserinfo.HMS">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>JUMP</code><em> = [' ', '.', ',', ';', '-', '/', "'", 'at', 'on', 'and', 'ad', 'm', 't', 'of', 'st', 'nd', 'rd', 'th']</em><a href="#dateutil.parser.parserinfo.JUMP">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>MONTHS</code><em> = [('Jan', 'January'), ('Feb', 'February'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'Sept', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')]</em><a href="#dateutil.parser.parserinfo.MONTHS">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>PERTAIN</code><em> = ['of']</em><a href="#dateutil.parser.parserinfo.PERTAIN">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>TZOFFSET</code><em> = {}</em><a href="#dateutil.parser.parserinfo.TZOFFSET">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>UTCZONE</code><em> = ['UTC', 'GMT', 'Z', 'z']</em><a href="#dateutil.parser.parserinfo.UTCZONE">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>WEEKDAYS</code><em> = [('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')]</em><a href="#dateutil.parser.parserinfo.WEEKDAYS">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>ampm</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.ampm">[source]</a><a href="#dateutil.parser.parserinfo.ampm">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>convertyear</code>(<em>year</em>, <em>century_specified=False</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.convertyear">[source]</a><a href="#dateutil.parser.parserinfo.convertyear">Â¶</a></dt>
<dd><p>Converts two-digit years to year within [-50, 49]
range of self._year (current local time)</p>
</dd></dl>
<dl>
<dt>
<code>hms</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.hms">[source]</a><a href="#dateutil.parser.parserinfo.hms">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>jump</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.jump">[source]</a><a href="#dateutil.parser.parserinfo.jump">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>month</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.month">[source]</a><a href="#dateutil.parser.parserinfo.month">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>pertain</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.pertain">[source]</a><a href="#dateutil.parser.parserinfo.pertain">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>tzoffset</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.tzoffset">[source]</a><a href="#dateutil.parser.parserinfo.tzoffset">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>utczone</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.utczone">[source]</a><a href="#dateutil.parser.parserinfo.utczone">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>validate</code>(<em>res</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.validate">[source]</a><a href="#dateutil.parser.parserinfo.validate">Â¶</a></dt>
<dd></dd></dl>
<dl>
<dt>
<code>weekday</code>(<em>name</em>)<a href="_modules/dateutil/parser/_parser.html#parserinfo.weekday">[source]</a><a href="#dateutil.parser.parserinfo.weekday">Â¶</a></dt>
<dd></dd></dl>
</dd></dl>
</div>
<div>
<h2>Warnings and Exceptions<a href="#warnings-and-exceptions">Â¶</a></h2>
<dl>
<dt>
<em>class </em><code>dateutil.parser.</code><code>ParserError</code><a href="_modules/dateutil/parser/_parser.html#ParserError">[source]</a><a href="#dateutil.parser.ParserError">Â¶</a></dt>
<dd><p>Exception subclass used for any failure to parse a datetime string.</p>
<p>This is a subclass of <code>ValueError</code>, and should be raised any time
earlier versions of <code>dateutil</code> would have raised <code>ValueError</code>.</p>
<p>New in version 2.8.1.</p>
</dd></dl>
<dl>
<dt>
<em>class </em><code>dateutil.parser.</code><code>UnknownTimezoneWarning</code><a href="_modules/dateutil/parser/_parser.html#UnknownTimezoneWarning">[source]</a><a href="#dateutil.parser.UnknownTimezoneWarning">Â¶</a></dt>
<dd><p>Raised when the parser finds a timezone it cannot parse into a tzinfo.</p>
<p>New in version 2.7.0.</p>
</dd></dl>
</div>
</div>
 </section>
 </div>||||I|||| dateutil
 stable
 * Overview
 * Changelog
 * Examples
 * Exercises
 * easter
 * parser
 + Functions
 + Classes
 + Warnings and Exceptions
 * relativedelta
 * rrule
 * tz
 * tz.win
 * utils
 * zoneinfo
 dateutil
 * Docs »
 * parser
 * Edit on GitHub

 parserÂ¶

 This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time.

 This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous. If an element of a date/time stamp is omitted, the following rules are applied:

 * If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour on a 12-hour clock ( 0 <= hour <= 12 ) must be specified if AM or PM is specified.
 * If a time zone is omitted, a timezone-naive datetime is returned.

 If any other elements are missing, they are taken from the datetime.datetime object passed to the parameter default . If this results in a day number exceeding the valid number of days per month, the value falls back to the end of the month.

 Additional resources about date/time string formats can be found below:

 * A summary of the international standard date and time notation
 * W3C Date and Time Formats
 * Time Formats (Planetary Rings Node)
 * CPAN ParseDate module
 * Java SimpleDateFormat Class

 FunctionsÂ¶

 parser.parse ( parserinfo=None, **kwargs ) [source] Â¶

 Parse a string in one of the supported formats, using the parserinfo parameters.

 Parameters: * timestr â A string containing a date/time stamp.  
 * parserinfo â A parserinfo object containing parameters for the parser. If None , the default arguments to the parserinfo constructor are used.
 

 The **kwargs parameter takes the following keyword arguments:

 * default â The default datetime object, if this is a datetime object and not None , elements specified in timestr replace elements in the default object.    
 * ignoretz â If set True , time zones in parsed strings are ignored and a naive datetime object is returned.    
 * tzinfos â      
      
 Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters ( tzname and tzoffset ) and returning a time zone.
      
 The timezones to which the names are mapped can be an integer offset from UTC in seconds or a tzinfo object.    
      
 >>> from dateutil.parser import parse     
 >>> from dateutil.tz import gettz     
 >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}     
 >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)     
 datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))     
 >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)     
 datetime.datetime(2012, 1, 19, 17, 21,     
 Parameters: tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))     
      
      
 This parameter is ignored if ignoretz is set.     
      
 * dayfirst â Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day ( True ) or month ( False ). If yearfirst is set to True , this distinguishes between YDM and YMD. If set to None , this value is retrieved from the current parserinfo object (which itself defaults to False ). 
 * yearfirst â Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If True , the first number is taken to be the year, otherwise the last number is taken to be the year. If this is set to None , the value is retrieved from the current parserinfo object (which itself defaults to False ). 
 * fuzzy â Whether to allow fuzzy parsing, allowing for string like âToday is January 1, 2047 at 8:21:00AMâ.    
 * fuzzy_with_tokens â      
      
 If True , fuzzy is automatically set to True, and the parser will return a tuple where the first element is the parsed datetime.datetime datetimestamp and the second element is a tuple containing the portions of the string which were ignored:  
      
 >>> from dateutil.parser import parse     
 >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)     
 (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))     
      
 Returns: Returns a datetime.datetime object or, if the fuzzy_with_tokens option is True , returns a tuple, the first element being a datetime.datetime object, the second a tuple containing the fuzzy tokens.   
      
 Raises: * ParserError â Raised for invalid or unknown string formats, if the provided tzinfo is not in a valid format, or if an invalid date would be created.    
 * OverflowError â Raised if the parsed date exceeds the largest valid C integer on your system.    
 
 classmethod parser.isoparse ( dt_str ) Â¶

 Parse an ISO-8601 datetime string into a datetime.datetime .

 An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is T in the official standard. Incomplete date formats (such as YYYY-MM ) may not be combined with a time portion.

 Supported date formats are:

 Common:

 * YYYY
 * YYYY-MM or YYYYMM
 * YYYY-MM-DD or YYYYMMDD

 Uncommon:

 * YYYY-Www or YYYYWww - ISO week (day defaults to 0)
 * YYYY-Www-D or YYYYWwwD - ISO week and day

 The ISO week and day numbering follows the same logic as datetime.date.isocalendar() .

 Supported time formats are:

 * hh
 * hh:mm or hhmm
 * hh:mm:ss or hhmmss
 * hh:mm:ss.ssssss (Up to 6 sub-second digits)

 Midnight is a special case for hh, as the standard supports both 00:00 and 24:00 as a representation. The decimal separator can be either a dot or a comma.

 Caution

 Support for fractional components other than seconds is part of the ISO-8601 standard, but is not currently implemented in this parser.

 Supported time zone offset formats are:

 * Z (UTC)
 * Â±HH:MM
 * Â±HHMM
 * Â±HH

 Offsets will be represented as dateutil.tz.tzoffset objects, with the exception of UTC, which will be represented as dateutil.tz.tzutc . Time zone offsets equivalent to UTC (such as +00:00) will also be represented as dateutil.tz.tzutc .

 Parameters: dt_str â A string or stream containing only an ISO-8601 datetime string 
 Returns: Returns a datetime.datetime representing the string. Unspecified components default to their lowest value.
 

 Warning

 As of version 2.7.0, the strictness of the parser should not be considered a stable part of the contract. Any valid ISO-8601 string that parses correctly with the default settings will continue to parse correctly in future versions, but invalid strings that currently fail (e.g. 2017-01-01T00:00+00:00:00 ) are not guaranteed to continue failing in future versions if they encode a valid date.

 New in version 2.7.0.

 ClassesÂ¶

 class dateutil.parser.parserinfo ( dayfirst=False, yearfirst=False ) [source] Â¶

 Class which handles what inputs are accepted. Subclass this to customize the language and acceptable values for each parameter.

 Parameters: * dayfirst â Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the day ( True ) or month ( False ). If yearfirst is set to True , this distinguishes between YDM and YMD. Default is False . 
 * yearfirst â Whether to interpret the first value in an ambiguous 3-integer date (e.g. 01/05/09) as the year. If True , the first number is taken to be the year, otherwise the last number is taken to be the year. Default is False .
 
 AMPM = [('am', 'a'), ('pm', 'p')]Â¶ HMS = [('h', 'hour', 'hours'), ('m', 'minute', 'minutes'), ('s', 'second', 'seconds')]Â¶ JUMP = [' ', '.', ',', ';', '-', '/', "'", 'at', 'on', 'and', 'ad', 'm', 't', 'of', 'st', 'nd', 'rd', 'th']Â¶ MONTHS = [('Jan', 'January'), ('Feb', 'February'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'Sept', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')]Â¶ PERTAIN = ['of']Â¶ TZOFFSET = {}Â¶ UTCZONE = ['UTC', 'GMT', 'Z', 'z']Â¶ WEEKDAYS = [('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')]Â¶ ampm ( name ) [source] Â¶ convertyear ( year, century_specified=False ) [source] Â¶

 Converts two-digit years to year within [-50, 49] range of self._year (current local time)

 hms ( name ) [source] Â¶ jump ( name ) [source] Â¶ month ( name ) [source] Â¶ pertain ( name ) [source] Â¶ tzoffset ( name ) [source] Â¶ utczone ( name ) [source] Â¶ validate ( res ) [source] Â¶ weekday ( name ) [source] Â¶

 Warnings and ExceptionsÂ¶

 class dateutil.parser.ParserError [source] Â¶

 Exception subclass used for any failure to parse a datetime string.

 This is a subclass of ValueError , and should be raised any time earlier versions of dateutil would have raised ValueError .

 New in version 2.8.1.

 class dateutil.parser.UnknownTimezoneWarning [source] Â¶

 Raised when the parser finds a timezone it cannot parse into a tzinfo.

 New in version 2.7.0.

 Next Previous

 © Copyright 2019, dateutil Revision 6b035517 .

 Built with Sphinx using a theme provided by Read the Docs.
 Read the Docs v: stable
 Versions latest stable 2.8.2 2.8.1 2.8.0 2.7.5 2.7.4 2.7.3 2.7.2 2.7.1 2.7.0 2.6.1 2.6.0 2.5.3 2.5.2 2.5.1 2.5.0 2.4.2 2.4.1 2.4.0 2.3 Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
dateutil
 
 
 
This module offers a generic date/time string parser which is able to parse
most known formats to represent a date and/or time.
This module attempts to be forgiving with regards to unlikely input formats,
returning a datetime object even for dates which are ambiguous. If an element
of a date/time stamp is omitted, the following rules are applied:
If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour
on a 12-hour clock (0 &lt;= hour &lt;= 12) must be specified if AM or PM is
specified.
If a time zone is omitted, a timezone-naive datetime is returned.
If any other elements are missing, they are taken from the
datetime.datetime object passed to the parameter default. If this
results in a day number exceeding the valid number of days per month, the
value falls back to the end of the month.
Additional resources about date/time string formats can be found below:
 A summary of the international standard date and time notation 
 W3C Date and Time Formats 
 Time Formats (Planetary Rings Node) 
 CPAN ParseDate module 
 Java SimpleDateFormat Class 
FunctionsÂ¶ 
parser. parse(parserinfo=None, **kwargs)[source] Â¶ 
 Parse a string in one of the supported formats, using the
parserinfo parameters.
  
 
 
 Parameters:  
 timestr â A string containing a date/time stamp.
 parserinfo â A  parserinfo  object containing parameters for the parser.
If None, the default arguments to the  parserinfo 
constructor are used.
The **kwargs parameter takes the following keyword arguments:
  
 
 
 Parameters:  
 default â The default datetime object, if this is a datetime object and not
None, elements specified in timestr replace elements in the
default object.
 ignoretz â If set True, time zones in parsed strings are ignored and a naive
datetime object is returned.
 tzinfos â Additional time zone names / aliases which may be present in the
string. This argument maps time zone names (and optionally offsets
from those time zones) to time zones. This parameter can be a
dictionary with timezone aliases mapping time zone names to time
zones or a function taking two parameters (tzname and
tzoffset) and returning a time zone.
The timezones to which the names are mapped can be an integer
offset from UTC in seconds or a tzinfo object.
  &gt;&gt;&gt; from dateutil.parser import parse
 &gt;&gt;&gt; from dateutil.tz import gettz
 &gt;&gt;&gt; tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")}
 &gt;&gt;&gt; parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos)
 datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200))
 &gt;&gt;&gt; parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos)
 datetime.datetime(2012, 1, 19, 17, 21,
 tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))
 
This parameter is ignored if ignoretz is set.
 dayfirst â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (True) or month (False). If
yearfirst is set to True, this distinguishes between YDM and
YMD. If set to None, this value is retrieved from the current
 parserinfo  object (which itself defaults to False).
 yearfirst â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the year. If True, the first number is taken to
be the year, otherwise the last number is taken to be the year. If
this is set to None, the value is retrieved from the current
 parserinfo  object (which itself defaults to False).
 fuzzy â Whether to allow fuzzy parsing, allowing for string like âToday is
January 1, 2047 at 8:21:00AMâ.
 fuzzy_with_tokens â If True, fuzzy is automatically set to True, and the parser
will return a tuple where the first element is the parsed
datetime.datetime datetimestamp and the second element is
a tuple containing the portions of the string which were ignored:
 &gt;&gt;&gt; from dateutil.parser import parse
&gt;&gt;&gt; parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True)
(datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at '))
 
 Returns:  Returns a datetime.datetime object or, if the
fuzzy_with_tokens option is True, returns a tuple, the
first element being a datetime.datetime object, the second
a tuple containing the fuzzy tokens.
 Raises:  
  ParserError  â Raised for invalid or unknown string formats, if the provided
tzinfo is not in a valid format, or if an invalid date would
be created.
 OverflowError â Raised if the parsed date exceeds the largest valid C integer on
your system.
 
classmethod  parser. isoparse(dt_str)Â¶ 
 Parse an ISO-8601 datetime string into a datetime.datetime.
An ISO-8601 datetime string consists of a date portion, followed
optionally by a time portion - the date and time portions are separated
by a single character separator, which is T in the official
standard. Incomplete date formats (such as YYYY-MM) may not be
combined with a time portion.
Supported date formats are:
Common:
 YYYY 
 YYYY-MM or YYYYMM 
 YYYY-MM-DD or YYYYMMDD 
Uncommon:
 YYYY-Www or YYYYWww - ISO week (day defaults to 0)
 YYYY-Www-D or YYYYWwwD - ISO week and day
The ISO week and day numbering follows the same logic as
datetime.date.isocalendar().
Supported time formats are:
 hh 
 hh:mm or hhmm 
 hh:mm:ss or hhmmss 
 hh:mm:ss.ssssss (Up to 6 sub-second digits)
Midnight is a special case for hh, as the standard supports both
00:00 and 24:00 as a representation. The decimal separator can be
either a dot or a comma.
Caution
Support for fractional components other than seconds is part of the
ISO-8601 standard, but is not currently implemented in this parser.
Supported time zone offset formats are:
 Z (UTC)
 Â±HH:MM 
 Â±HHMM 
 Â±HH 
Offsets will be represented as  dateutil.tz.tzoffset  objects,
with the exception of UTC, which will be represented as
 dateutil.tz.tzutc . Time zone offsets equivalent to UTC (such
as +00:00) will also be represented as  dateutil.tz.tzutc .
  
 
 
 Parameters:  dt_str â A string or stream containing only an ISO-8601 datetime string
 Returns: Returns a datetime.datetime representing the string.
Unspecified components default to their lowest value.
Warning
As of version 2.7.0, the strictness of the parser should not be
considered a stable part of the contract. Any valid ISO-8601 string
that parses correctly with the default settings will continue to
parse correctly in future versions, but invalid strings that
currently fail (e.g. 2017-01-01T00:00+00:00:00) are not
guaranteed to continue failing in future versions if they encode
a valid date.
New in version 2.7.0.
 
ClassesÂ¶ 
class  dateutil.parser. parserinfo(dayfirst=False, yearfirst=False)[source] Â¶ 
 Class which handles what inputs are accepted. Subclass this to customize
the language and acceptable values for each parameter.
  
 
 
 Parameters:  
 dayfirst â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the day (True) or month (False). If
yearfirst is set to True, this distinguishes between YDM
and YMD. Default is False.
 yearfirst â Whether to interpret the first value in an ambiguous 3-integer date
(e.g. 01/05/09) as the year. If True, the first number is taken
to be the year, otherwise the last number is taken to be the year.
Default is False.
AMPM  = [('am', 'a'), ('pm', 'p')] Â¶ 
  
HMS  = [('h', 'hour', 'hours'), ('m', 'minute', 'minutes'), ('s', 'second', 'seconds')] Â¶ 
  
JUMP  = [' ', '.', ',', ';', '-', '/', "'", 'at', 'on', 'and', 'ad', 'm', 't', 'of', 'st', 'nd', 'rd', 'th'] Â¶ 
  
MONTHS  = [('Jan', 'January'), ('Feb', 'February'), ('Mar', 'March'), ('Apr', 'April'), ('May', 'May'), ('Jun', 'June'), ('Jul', 'July'), ('Aug', 'August'), ('Sep', 'Sept', 'September'), ('Oct', 'October'), ('Nov', 'November'), ('Dec', 'December')] Â¶ 
  
PERTAIN  = ['of'] Â¶ 
  
TZOFFSET  = {} Â¶ 
  
UTCZONE  = ['UTC', 'GMT', 'Z', 'z'] Â¶ 
  
WEEKDAYS  = [('Mon', 'Monday'), ('Tue', 'Tuesday'), ('Wed', 'Wednesday'), ('Thu', 'Thursday'), ('Fri', 'Friday'), ('Sat', 'Saturday'), ('Sun', 'Sunday')] Â¶ 
  
ampm(name)[source] Â¶ 
  
convertyear(year, century_specified=False)[source] Â¶ 
 Converts two-digit years to year within [-50, 49]
range of self._year (current local time)
 
hms(name)[source] Â¶ 
  
jump(name)[source] Â¶ 
  
month(name)[source] Â¶ 
  
pertain(name)[source] Â¶ 
  
tzoffset(name)[source] Â¶ 
  
utczone(name)[source] Â¶ 
  
validate(res)[source] Â¶ 
  
weekday(name)[source] Â¶ 
  
 
Warnings and ExceptionsÂ¶ 
class  dateutil.parser. ParserError [source] Â¶ 
 Exception subclass used for any failure to parse a datetime string.
This is a subclass of ValueError, and should be raised any time
earlier versions of dateutil would have raised ValueError.
New in version 2.8.1.
 
class  dateutil.parser. UnknownTimezoneWarning [source] Â¶ 
 Raised when the parser finds a timezone it cannot parse into a tzinfo.
New in version 2.7.0.
parserÂ¶
https://dateutil.readthedocs.io/en/stable/parser.html
https://www.geeksforgeeks.org/nlp-using-dateutil-to-parse-dates/
NLP  Using dateutil to parse dates.
2019-06-17
M mathemagic Follow
<div><div>
<p>
</p>
</div><div>
<p>The <strong>parser </strong>module can parse datetime strings in many more formats. There can be no better library than <strong>dateutil</strong> to parse dates and times in Python. To lookup the timezones, the <strong>tz </strong>module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.</p>
<p><strong>Installation : </strong><br/>
dateutil can be installed using pip or easy_install, that is, <strong>sudo pip install dateutil==2.0</strong> or <strong>sudo easy_install dateutil==2.0</strong>. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at <a href="http://labix.org/python-dateutil">http://labix.org/python-dateutil</a>.</p>
<p><strong>Code: Parsing Examples </strong></p>
<div>
<p><code>from</code> <code>dateutil </code><code>import</code> <code>parser </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'Thu Sep 25 10:36:28 2010'</code><code>)) </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'Thursday, 25. September 2010 10:36AM'</code><code>)) </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'9 / 25 / 2010 10:36:28'</code><code>)) </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'9 / 25 / 2010'</code><code>)) </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'2010-09-25T10:36:28Z'</code><code>)) </code></p>
</div>
<p><strong>Output : </strong></p>
<pre>datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 10, 36)
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 0, 0)
datetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())</pre>
<p>All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.<br/>
<strong>How it works : </strong></p>
<ul>
<li>The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions. </li>
<li>The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format. </li>
<li>The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem.</li>
<li>It can correctly parse dates in the latter format if it is set to True. </li>
</ul>
<div>
<p><code>parser.parse(</code><code>'16 / 6/2019'</code><code>, dayfirst </code><code>=</code> <code>True</code><code>) </code></p>
</div>
<p><strong>Output :</strong> </p>
<pre>datetime.datetime(2016, 6, 16, 0, 0)</pre>
<p>Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011.</p>
<div>
<p><code>print</code> <code>(parser.parse(</code><code>'11-6-19'</code><code>)) </code></p>
<p><code>print</code> <code>(parser.parse(</code><code>'10-6-25'</code><code>, yearfirst </code><code>=</code> <code>True</code><code>)) </code></p>
</div>
<p><strong>Output :</strong> </p>
<pre>datetime.datetime(2019, 11, 6, 0, 0)
datetime.datetime(2011, 6, 19, 0, 0)</pre>
<p>dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. <strong>parse()</strong> will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True.</p>
<br/> <br/>
<div>
<p>
</p>
</div> <div> <p> <h3>Please <u></u> to comment...</h3></p>
</div>
</div></div>||||I|||| Skip to content
 * Tutorials
 + Python Tutorial
 o Taking Input in Python
 o Python Operators
 o Python Data Types
 - Python Numbers
 - Python String
 - Python Lists
 - Python Tuples
 - Sets in Python
 - Python Dictionary
 o Python Loops and Control Flow
 - Python If Else
 - Python For Loops
 - Python While Loops
 - Python Breaks
 - Python Continue Statement
 - Python Pass Statement
 o Python Functions
 o Python OOPS Concept
 o Python Data Structures
 - Python DSA
 - Linked List
 - Stack
 - Queue
 - Tree
 - Heap
 - Hashing
 - Graph
 - Sets
 - Map
 - Advance Data Structure
 - Sorting Algorithms
 - Searching Algorithms
 o Python Exception Handling
 o Python File Handling
 o Python Exercises
 - Python List Exercise
 - Python String Exercise
 - Python Tuple Exercise
 - Python Dictionary Exercise
 - Python Set Exercise
 - Python Design Patterns
 - Python Programming Examples
 - Python Practice Questions
 + Java
 o Java Programming Language
 - Java Tutorial
 - Data Types
 - Variables
 - Operators
 * Operators in Java
 * Arithmetic Operators
 * Unary Operators
 * Assignment Operators
 * Relational Operators
 * Logical Operators
 * Ternary Operators
 - Flow Control in Java
 * Flow Control
 * if Statement
 * if-else Statement
 * if-else-if Ladder
 * Continue Statement
 * Break Statement
 * Return Statement
 - Loops in Java
 * Loops
 * do-while Loop
 * For Loop
 * For-each Loop
 - Methods
 - Strings
 - Arrays
 - OOPs Concepts
 * OOPs Concepts
 * Classes and Objects
 * Access Modifiers
 * Inheritance
 * Abstraction
 * Encapsulation
 * Polymorphism
 - Interface
 - Packages
 - Multithreading
 - File Handling
 - Regular Expression
 o Java Collections
 - Java Collections
 - Collection Class
 - List Interface
 - ArrayList
 - Vector Class
 - Stack Class
 - LinkedList Class
 - Queue Interface
 - Set Interface
 - HashSet Class
 - TreeSet
 - Map Interface
 - HashMap Class
 - HashTable Class
 - Iterator
 - Comparator
 - Collection Interview Questions
 o Java 8 Tutorial
 o Java Programs
 - Java Programming Examples
 - Java Array Programs
 - Java String Programs
 - Java Date-Time Programs
 - Java File Handling Programs
 - Java Collection Programs
 - Java JDBC Programs
 - Java Apache POI Programs
 - Java OpenCV Programs
 o Java Interview Questions
 - Java Interview Questions
 - Core Java Interview Questions-Freshers
 - Java Multithreading Interview Questions
 - OOPs Interview Questions and Answers
 o Java Exercises
 o Java Quiz
 - Java Quiz
 - Core Java MCQ
 o Java Projects
 o Advance Java
 - Spring Tutorial
 - Spring Boot Tutorial
 - Spring Boot Interview Questions
 - Spring MVC Tutorial
 - Spring MVC Interview Questions
 - Hibernate Tutorial
 - Hibernate Interview Questions
 + Programming Languages
 o C
 o C++
 o JavaScript
 o PHP
 o R Tutorial
 o C#
 o SQL
 o Scala
 o Perl
 o Go Language
 o Kotlin
 + System Design
 o System Design Tutorial
 - What is System Design
 - Key Terminologies in System Design
 - Analysis and Architecture of Systems
 - Scalability in System Design
 - Databases in System Design
 - High Level Design or HLD
 - Low Level Design or LLD
 - Communication Protocols
 - Web Servers and Proxies
 - Case Studies in Designing Systems
 - Complete System Design Tutorial
 o Software Design Patterns
 - Factory Pattern
 - Observer Pattern
 - Singleton Design Pattern
 - Decorator Pattern
 - Strategy Pattern
 - Adapter Pattern
 - Command Pattern
 - Iterator Pattern
 - Prototype Design Pattern
 - All Design Patterns
 o System Design Roadmap
 o Top 10 System Design Interview Questions and Answers
 + Interview Corner
 o Company Preparation
 o Top Topics
 o Practice Company Questions
 o Interview Experiences
 o Experienced Interviews
 o Internship Interviews
 o Competitive Programming
 o Multiple Choice Quizzes
 o Aptitude for Placements
 + Computer Science Subjects
 o Mathematics
 o Operating System
 o DBMS
 o Computer Networks
 o Computer Organization and Architecture
 o Theory of Computation
 o Compiler Design
 o Digital Logic
 o Software Engineering
 + DevOps
 o GIT
 o AWS
 o Docker
 o Kubernetes
 o Microsoft Azure Tutorial
 o Google Cloud Platform
 + Linux
 o Linux Tutorial
 o Linux Commands A-Z
 o Linux Commands Cheatsheet
 o 25 Basic Linux Commands
 o File Mangement in Linux
 o File Permission Commands
 - chmod Command
 - chown Command
 - chgrp Command
 - unmask Command
 o Linux System Administration
 o Linux File System
 o Linux Shell Scripting
 o Linux Networking
 o Linux Firewall
 o Linux Interview Questions
 + Software Testing
 o Software Testing Tutorial
 - Software Testing Tutorial
 - What is Software Testing
 - Principles of Software Testing
 - Types of Software Testing
 - Levels of Software Testing
 - Automation Testing
 - Manual Testing
 o Testing Tools
 - Software Testing Tools
 - Defect Testing Tools
 - Cross-Browser Testing Tools
 - Integration Testing Tool
 - Unit Testing Tools
 - Mobile Testing Tools
 - GUI Testing Tool
 - Security Testing Tools
 - Penetration Testing Tools
 o Selenium
 - Selenium Tutorial
 - Selenium Basics
 - Selenium Python
 o Jira
 - Jira Tutorial
 - JIRA Installation
 - JIRA Login
 - JIRA Dashboard
 o Software Engineering
 - Software Engineering Tutorial
 - Software Development Life Cycle (SDLC)
 - Software Characteristics
 - Software Quality
 - Waterfall Model
 - Iterative Waterfall Model
 - Spiral Model
 - Prototyping Model
 - Incremental Process Model
 o Interview Questions
 - Software Testing Interview Questions
 - Automation Testing Interview Questions
 - Manual Testing Interview Questions
 - Software Engineering Interview Questions
 - Penetration Testing Interview Questions
 - API Testing Interview Questions
 o Postman
 - Postman Tutorial
 - Postman for API Development
 - Download and Install Postman
 - API Testing Using Postman
 - Generate HTML Report for Postman
 + Databases
 o DBMS Tutorial
 o SQL Tutorial
 o PostgreSQL Tutorial
 o MongoDB Tutorial
 o SQL Interview Questions
 o MySQL Interview Questions
 o PL/SQL Interview Questions
 + Android
 o Android Tutorial
 o Android Studio Tutorial
 o Kotlin For Android
 o Android Projects
 o Android Interview Questions
 o 6 Weeks of Android App Development
 + Excel
 o MS Excel Tutorial
 o Introduction to MS Excel
 o Data Analysis in Excel
 o Basic Excel Formulas & Functions
 o Data Analysis in Advanced Excel
 o Workbooks
 o Statistical Functions
 o Data Visualization in Excel
 o Pivot Tables in Excel
 o Excel Spreadsheets in Python
 o Basic Excel Shortcuts
 + Mathematics
 o Number System
 o Algebra
 o Linear Algebra
 o Trigonometry
 o Set Theory
 o Statistics
 o Probability
 o Geometry
 o Mensuration
 o Logarithms
 o Calculus
 + Commerce
 o Business Studies
 o Accountancy
 o Microeconomics
 o Statistics for Economics
 o Macroeconomics
 o Human Resource Management (HRM)
 o Management
 o Income Tax
 o Finance
 o Commerce Complete Guide
 + SEO-Search Engine Optimization
 o What is SEO
 o Search Engine Optimization Basics
 o Types of SEO
 o Keyword Optimization in SEO
 o Backlinks in SEO
 o SEO Blogs
 o Mobile SEO
 o SEO Complete Reference
 + Aptitude
 o Aptitude Question and Answers
 o Quantitative Aptitude
 o Logical Reasoning
 o Verbal Ability
 * DSA
 + Data Structures
 o Arrays
 o Matrix
 o Strings
 o Linked List
 - Singly Linked List
 - Doubly Linked List
 - Circular Linked List
 - Doubly Circular Linked List
 - Linked List Tutorial
 o Stack
 o Queue
 o Tree
 - Generic Tree
 - Binary Tree
 - Binary Search Tree
 - AVL Tree
 - B Tree
 - B+ Tree
 - Red Black Tree
 - Tree Data Structure Tutorial
 o Heap
 o Hashing
 o Graph
 o Set Data Structure
 o Map Data Structure
 o Advanced Data Structure
 o Data Structures Tutorial
 + Algorithms
 o Analysis of Algorithms
 - Design and Analysis of Algorithms
 - Asymptotic Analysis
 - Asymptotic Notations
 - Worst, Average and Best Cases
 o Searching Algorithms
 - Linear Search
 - Binary Search
 - Searching Algorithms Tutorial
 o Sorting Algorithms
 - Selection Sort
 - Bubble Sort
 - Insertion Sort
 - Merge Sort
 - Quick Sort
 - Heap Sort
 - Counting Sort
 - Radix Sort
 - Bucket Sort
 - Sorting Algorithms Tutorial
 o Greedy Algorithms
 o Dynamic Programming
 o Graph Algorithms
 o Pattern Searching
 o Recursion
 o Backtracking
 o Divide and Conquer
 o Mathematical Algorithms
 o Geometric Algorithms
 o Bitwise Algorithms
 o Randomized Algorithms
 o Branch and Bound
 o Algorithms Tutorial
 + DSA Tutorial
 + Practice
 o All DSA Problems
 o Problem of the Day
 o Company Wise Coding Practice
 - Amazon
 - Microsoft
 - Flipkart
 - Explore All
 o GfG SDE Sheet
 o Practice Problems Difficulty Wise
 - School
 - Basic
 - Easy
 - Medium
 - Hard
 o Language Wise Coding Practice
 - CPP
 - Java
 - Python
 o Curated DSA Lists
 - Beginner's DSA Sheet
 - Top 50 Array Problems
 - Top 50 String Problems
 - Top 50 DP Problems
 - Top 50 Graph Problems
 - Top 50 Tree Problems
 + Competitive Programming
 + Company Wise SDE Sheets
 o Facebook SDE Sheet
 o Amazon SDE Sheet
 o Apple SDE Sheet
 o Netflix SDE Sheet
 o Google SDE Sheet
 + DSA Cheat Sheets
 o SDE Sheet
 o DSA Sheet for Beginners
 o FAANG Coding Sheet
 o Product-Based Coding Sheet
 o Company-Wise Preparation Sheet
 + Top Interview Questions
 o Top 100 DSA Interview Questions Topic-wise
 + Puzzles
 o All Puzzles
 o Top 100 Puzzles Asked In Interviews
 o Top 20 Puzzles Commonly Asked During SDE Interviews
 * Data Science
 + Python Tutorial
 + R Tutorial
 + Machine Learning
 + Data Science using Python
 + Data Science using R
 + Data Science Packages
 o Pandas Tutorial
 o NumPy Tutorial
 + Data Visualization
 o Python Data Visualization Tutorial
 o Data Visualization with R
 + Data Analysis
 o Data Analysis with Python
 o Data Analysis with R
 + Deep Learning
 + NLP Tutorial
 * Web Tech
 + HTML Tutorial
 + CSS Tutorial
 + JavaScript Tutorial
 + PHP Tutorial
 + ReactJS Tutorial
 + NodeJS Tutorial
 + AngularJS Tutorial
 + Bootstrap Tutorial
 + Web Development Using Python
 o Django
 - Getting started with Django
 - Create an App in Django
 - Views In Django
 - Django Templates
 - Django URL patterns
 - Django Admin Interface
 - Django Models
 - MySQL Databased with Django
 - Django CRUD
 - Django Forms
 - Django Static File
 - Projects for Beginners
 - Django Tutorial
 o Flask
 - Web Development Using Flask
 - Flask App Routing
 - URL building in Flask
 - Flask Templates
 - Templating With Jinja2 in Flask
 - Flask Model
 - Database with Flask SQL Alchemy
 - Authentication with Flask
 - WTForms in Flask
 - Static files in Flask
 - Python Flask Projects
 - Flask Interview Questions
 o Frontend Projects
 - Building a Survey Form using HTML and CSS
 - Food delivery system using HTML and CSS
 - ToDo webapp using Django
 - Building Blog CMS
 - Add Pagination in Django
 - Tailwind CSS with Django
 - Django with Reactjs
 o Postman
 o Github
 + JSON Tutorial
 + TypeScript Tutorial
 + Wordpress Tutorial
 + Web Design
 + Web Browsers
 o Google Chrome
 o Mozilla Firefox
 o Apple Safari
 o Microsoft Edge
 o Tor
 + Cheat Sheets
 o HTML Cheat Sheet
 o CSS Cheat Sheet
 o JavaScript Cheat Sheet
 o React Cheat Sheet
 o Angular Cheat Sheet
 o jQuery Cheat Sheet
 o Bootstrap Cheat Sheet
 + JavaScript Projects
 + Learn Complete Web Development
 + File Formats
 * Courses
 + Coding for Everyone
 + DSA to Development
 + Machine Learning and Data Science
 + DSA Courses
 o Data Structure & Algorithm(C++/JAVA)
 o Data Structure & Algorithm(Python)
 o Data Structure & Algorithm(JavaScript)
 + Programming Languages
 o CPP
 o Java
 o Python
 o JavaScript
 o C
 * 
 * 
 * 
 * 
 + 
 + Python Basics
 + Interview Questions
 + Python Quiz
 + Popular Packages
 + Python Projects
 + Practice Python
 + AI With Python
 + Learn Python3
 + Python Automation
 + Python Web Dev
 + DSA with Python
 + Python OOPs
 + Lists
 + Strings
 + Dictionaries
 ▲
 Open In App
 + NLP | Using dateutil to parse dates.
 + Create Python Datetime from string
 + Python - Extract date in String
 + Parsing DateTime strings containing microseconds in Python
 + Python - Validate String date format
 + ctime() Function Of Datetime.date Class In Python
 + fromisoformat() Function Of Datetime.date Class In Python
 + PHP | date_parse() Function
 + Perl - Extracting Date from a String using Regex
 + PHP | date_parse_from_format() Function
 + Useful Date and Time Functions in PL/SQL
 + JSTL Formatting Tag
 + Convert string into date using JavaScript
 + Ruby | Date asctime() function
 + Lex program to check if a Date is valid or not
 + DateFormat parse(string , ParsePosition) Method in Java with Examples
 + Parsing Date and Time in R Programming - strptime() Function
 + Extracting all present dates in any given String using Regular Expressions
 + Java Program to Convert String to Date
 + Parsing Time in Golang
 + Removing stop words with NLTK in Python
 + Decision Tree
 + Linear Regression in Machine learning
 + Agents in Artificial Intelligence
 + Plotting Histogram in Python using Matplotlib
 + One Hot Encoding in Machine Learning
 + Best Python libraries for Machine Learning
 + Introduction to Hill Climbing | Artificial Intelligence
 + Clustering in Machine Learning
 + Digital Image Processing Basics

 NLP | Using dateutil to parse dates.

 Last Updated : 18 Jun, 2019
 Improve


 + 
 + 
 + 
 Improve
 Like Article
 Like
 Save
 Share
 Report

 The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.

 Installation :
 dateutil can be installed using pip or easy_install, that is, sudo pip install dateutil==2.0 or sudo easy_install dateutil==2.0. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at http://labix.org/python-dateutil.

 Code: Parsing Examples




 # importing library 
 from dateutil import parser 
 print (parser.parse('Thu Sep 25 10:36:28 2010')) 
 print (parser.parse('Thursday, 25. September 2010 10:36AM'))
 print (parser.parse('9 / 25 / 2010 10:36:28')) 
 print (parser.parse('9 / 25 / 2010')) 
 print (parser.parse('2010-09-25T10:36:28Z')) 
 

 Output :

 
 datetime.datetime(2010, 9, 25, 10, 36, 28)
 datetime.datetime(2010, 9, 25, 10, 36)
 datetime.datetime(2010, 9, 25, 10, 36, 28)
 datetime.datetime(2010, 9, 25, 0, 0)
 datetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())

 All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.
 How it works :

 + The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions.
 + The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format.
 + The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem.
 + It can correctly parse dates in the latter format if it is set to True.




 parser.parse('16 / 6/2019', dayfirst = True)
 

 Output :

 datetime.datetime(2016, 6, 16, 0, 0)

 Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011.




 print (parser.parse('11-6-19')) 
 print (parser.parse('10-6-25', yearfirst = True))
 

 Output :

 datetime.datetime(2019, 11, 6, 0, 0)
 datetime.datetime(2011, 6, 19, 0, 0)

 dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. parse() will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True.



 Like Article

 Suggest improvement


 Next
 Create Python Datetime from string
 Share your thoughts in the comments
 Add Your Comment

 Please Login to comment...

 Similar Reads

 How to Install python-dateutil on MacOS?
 Python - Find consecutive dates in a list of dates
 Python - Generate k random dates between two other dates
 Read, Write and Parse JSON using Python
 Parse XML using Minidom in Python
 How to Search the Parse Tree using BeautifulSoup?
 Processing text using NLP | Basics
 NLP | Chunking using Corpus Reader
 NLP | Customization Using Tagged Corpus Reader
 Project Idea - Searching news from Old Newspaper using NLP

 M

 mathemagic
 Follow




 Article Tags :
 + Python-nltk
 + AI-ML-DS
 + Machine Learning
 + NLP
 + Python




 Practice Tags :
 + Machine Learning
 + python




 A-143, 9th Floor, Sovereign Corporate Tower, Sector-136, Noida, Uttar Pradesh - 201305
 + Company
 + About Us
 + Legal
 + Careers
 + In Media
 + Contact Us
 + Advertise with us
 + GFG Corporate Solution
 + Placement Training Program
 + Explore
 + Hack-A-Thons
 + GfG Weekly Contest
 + DSA in JAVA/C++
 + Master System Design
 + Master CP
 + GeeksforGeeks Videos
 + Geeks Community
 + Languages
 + Python
 + Java
 + C++
 + PHP
 + GoLang
 + SQL
 + R Language
 + Android Tutorial
 + Tutorials Archive
 + DSA
 + Data Structures
 + Algorithms
 + DSA for Beginners
 + Basic DSA Problems
 + DSA Roadmap
 + Top 100 DSA Interview Problems
 + DSA Roadmap by Sandeep Jain
 + All Cheat Sheets
 + Data Science & ML
 + Data Science With Python
 + Data Science For Beginner
 + Machine Learning Tutorial
 + ML Maths
 + Data Visualisation Tutorial
 + Pandas Tutorial
 + NumPy Tutorial
 + NLP Tutorial
 + Deep Learning Tutorial
 + HTML & CSS
 + HTML
 + CSS
 + Web Templates
 + CSS Frameworks
 + Bootstrap
 + Tailwind CSS
 + SASS
 + LESS
 + Web Design
 + Django Tutorial
 + Python Tutorial
 + Python Programming Examples
 + Python Projects
 + Python Tkinter
 + Web Scraping
 + OpenCV Tutorial
 + Python Interview Question
 + Computer Science
 + Operating Systems
 + Computer Network
 + Database Management System
 + Software Engineering
 + Digital Logic Design
 + Engineering Maths
 + DevOps
 + Git
 + AWS
 + Docker
 + Kubernetes
 + Azure
 + GCP
 + DevOps Roadmap
 + Competitive Programming
 + Top DS or Algo for CP
 + Top 50 Tree
 + Top 50 Graph
 + Top 50 Array
 + Top 50 String
 + Top 50 DP
 + Top 15 Websites for CP
 + System Design
 + High Level Design
 + Low Level Design
 + UML Diagrams
 + Interview Guide
 + Design Patterns
 + OOAD
 + System Design Bootcamp
 + Interview Questions
 + JavaScript
 + JavaScript Examples
 + TypeScript
 + ReactJS
 + NextJS
 + AngularJS
 + NodeJS
 + Lodash
 + Web Browser
 + Preparation Corner
 + Company-Wise Recruitment Process
 + Resume Templates
 + Aptitude Preparation
 + Puzzles
 + Company-Wise Preparation
 + School Subjects
 + Mathematics
 + Physics
 + Chemistry
 + Biology
 + Social Science
 + English Grammar
 + World GK
 + Management & Finance
 + Management
 + HR Management
 + Finance
 + Income Tax
 + Organisational Behaviour
 + Marketing
 + Free Online Tools
 + Typing Test
 + Image Editor
 + Code Formatters
 + Code Converters
 + Currency Converter
 + Random Number Generator
 + Random Password Generator
 + More Tutorials
 + Software Development
 + Software Testing
 + Product Management
 + SAP
 + SEO - Search Engine Optimization
 + Linux
 + Excel
 + GeeksforGeeks Videos
 + DSA
 + Python
 + Java
 + C++
 + Data Science
 + CS Subjects
 @GeeksforGeeks, Sanchhaya Education Private Limited , All rights reserved
 We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Got It !

 What kind of Experience do you want to share?

 Interview Experiences
 Admission Experiences
 Career Compass for School Students
 Work Experiences
 Campus Experiences
 Competitive Exam Experiences
 Can't choose a topic to write? click here for suggested topics
 Write and publish your own Article
The parser module can parse datetime strings in many more formats. There can be no better library than dateutil to parse dates and times in Python. To lookup the timezones, the tz module provides everything. When these modules are combined, they make it very easy to parse strings into timezone-aware datetime objects.
 Installation :  
dateutil can be installed using pip or easy_install, that is, sudo pip install dateutil==2.0 or sudo easy_install dateutil==2.0. 2.0 version for Python 3 compatibility is required. The complete documentation can be found at http://labix.org/python-dateutil.
 Code: Parsing Examples  
 from dateutil  import parser  
 print (parser.parse( 'Thu Sep 25 10:36:28 2010' ))  
 print (parser.parse( 'Thursday, 25. September 2010 10:36AM' ))  
 print (parser.parse( '9 / 25 / 2010 10:36:28' ))  
 print (parser.parse( '9 / 25 / 2010' ))  
 print (parser.parse( '2010-09-25T10:36:28Z' ))  
 Output :  
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 10, 36)
datetime.datetime(2010, 9, 25, 10, 36, 28)
datetime.datetime(2010, 9, 25, 0, 0)
datetime.datetime(2010, 9, 25, 10, 36, 28, tzinfo=tzutc())
All it takes is importing the parser module and calling the parse() function with a datetime string. The parser can return a sensible datetime object, but it cannot parse the string, it will raise a ValueError.
How it works :  
The parser instead of looking for recognizable tokens, guess what those tokens refer to. It doesn’t use regular expressions. 
The order of these tokens matters as it uses a date format that looks like Month/Day/Year (the default order), while others use a Day/Month/Year format. 
The parse() function takes an optional keyword argument, dayfirst, which defaults to False to deal with this problem.
It can correctly parse dates in the latter format if it is set to True. 
 parser.parse( '16 / 6/2019' , dayfirst  = True )  
 Output : 
datetime.datetime(2016, 6, 16, 0, 0)
Another ordering issue can occur with two-digit years. but ’11-6-19′ is an ambiguous date format. Since dateutil defaults to the Month-Day-Year format, ’11-6-19′ is parsed to the year 2019. But if yearfirst = True is passed into parse(), it can be parsed to the year 2011.
 print (parser.parse( '11-6-19' ))  
 print (parser.parse( '10-6-25' , yearfirst  = True ))  
 Output : 
datetime.datetime(2019, 11, 6, 0, 0)
datetime.datetime(2011, 6, 19, 0, 0)
dateutil parser can also do fuzzy parsing and allows to ignore extraneous characters in a datetime string. parse() will raise a ValueError with the default value of False, when it encounters unknown tokens. A datetime object can usually be returned, if fuzzy = True.
 
   Please   to comment...
NLP  Using dateutil to parse dates.
https://www.geeksforgeeks.org/nlp-using-dateutil-to-parse-dates/
https://www.programcreek.com/python/example/98372/dateutil.parser.parse
Python Examples of dateutil.parser.parse
2003-09-25
None
<div><div>
<p>
The following are 
code examples of .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
, or try <a href="https://www.programcreek.com/python">the search function
</a>.
</p>
<p>Example #1</p>
<div>
<pre>def __new__(cls, t, snap=0):
 if isinstance(t, (str, bytes)) and t.isdigit():
 t = int(t)
 if not isinstance(t, (str, bytes)):
 from dateutil.tz import tzutc
 return datetime.fromtimestamp(t // 1000, tz=tzutc())
 try:
 units = ["weeks", "days", "hours", "minutes", "seconds"]
 diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
 if len(diffs) == 1:
 # Snap &gt; 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
 snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
 snap_units.pop("day", None)
 snap_units.update(microsecond=0)
 ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
 cls._precision[ts] = snap_units
 return ts
 return dateutil_parse(t)
 except (ValueError, OverflowError, AssertionError):
 raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t)) </pre>
</div>
<p>Example #2</p>
<div>
<pre>def as_date(val):
 '''Casts the value to a ``datetime.date`` object if possible
 Else raises ``TypeError``
 '''
 # Important to check if datetime first because datetime.date objects
 # pass the isinstance(obj, datetime.date) test
 if isinstance(val, datetime.datetime):
 return val.date()
 elif isinstance(val, datetime.date):
 return val
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).date()
 else:
 raise TypeError(
 'date cannot be of type "{}".'.format(type(val)) +
 ' It must be able to be cast to a datetime.date') </pre>
</div>
<p>Example #3</p>
<div>
<pre>def test_ybd(self):
 # If we have a 4-digit year, a non-numeric month (abbreviated or not),
 # and a day (1 or 2 digits), then there is no ambiguity as to which
 # token is a year/month/day. This holds regardless of what order the
 # terms are in and for each of the separators below.
 seps = ['-', ' ', '/', '.']
 year_tokens = ['%Y']
 month_tokens = ['%b', '%B']
 day_tokens = ['%d']
 if PLATFORM_HAS_DASH_D:
 day_tokens.append('%-d')
 prods = itertools.product(year_tokens, month_tokens, day_tokens)
 perms = [y for x in prods for y in itertools.permutations(x)]
 unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]
 actual = datetime(2003, 9, 25)
 for fmt in unambig_fmts:
 dstr = actual.strftime(fmt)
 res = parse(dstr)
 self.assertEqual(res, actual) </pre>
</div>
<p>Example #4</p>
<div>
<pre>def test_get_course_enrollments(self, query_params, filter_args):
 expected_data = CourseEnrollment.objects.filter(**filter_args)
 request = APIRequestFactory().get(self.request_path + query_params)
 force_authenticate(request, user=self.staff_user)
 view = self. view_class.as_view({'get': 'list'})
 response = view(request)
 assert response.status_code == 200
 assert set(response.data.keys()) == set(
 ['count', 'next', 'previous', 'results',])
 assert len(response.data['results']) == len(expected_data)
 for data in response.data['results']:
 db_rec = expected_data.get(id=data['id'])
 assert parse(data['created']) == db_rec.created </pre>
</div>
<p>Example #5</p>
<div>
<pre>def as_datetime(val):
 '''
 TODO: Add arg flag to say if caller wants end of day, beginning of day
 or a particular time of day if the param is a datetime.date obj
 '''
 if isinstance(val, datetime.datetime):
 return val
 elif isinstance(val, datetime.date):
 # Return the end of the day, set timezone to be UTC
 return datetime.datetime(
 year=val.year,
 month=val.month,
 day=val.day,
 ).replace(tzinfo=utc)
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).replace(tzinfo=utc)
 else:
 raise TypeError(
 'value of type "{}" cannot be converted to a datetime object'.format(
 type(val))) </pre>
</div>
<p>Example #6</p>
<div>
<pre>def testParseUnicodeWords(self):
 class rus_parserinfo(parserinfo):
 MONTHS = [("янв", "Январь"),
 ("фев", "Февраль"),
 ("мар", "Март"),
 ("апр", "Апрель"),
 ("май", "Май"),
 ("июн", "Июнь"),
 ("июл", "Июль"),
 ("авг", "Август"),
 ("сен", "Сентябрь"),
 ("окт", "Октябрь"),
 ("ноя", "Ноябрь"),
 ("дек", "Декабрь")]
 self.assertEqual(parse('10 Сентябрь 2015 10:20',
 parserinfo=rus_parserinfo()),
 datetime(2015, 9, 10, 10, 20)) </pre>
</div>
<p>Example #7</p>
<div>
<pre>def __deserialize_date(self, string):
 """Deserializes string to date.
 :param string: str.
 :return: date.
 """
 try:
 from dateutil.parser import parse
 return parse(string).date()
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason="Failed to parse `{0}` as date object".format(string)
 ) </pre>
</div>
<p>Example #8</p>
<div>
<pre>def __deserialize_datatime(self, string):
 """Deserializes string to datetime.
 The string should be in iso8601 datetime format.
 :param string: str.
 :return: datetime.
 """
 try:
 from dateutil.parser import parse
 return parse(string)
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason=(
 "Failed to parse `{0}` as datetime object"
 .format(string)
 )
 ) </pre>
</div>
<p>Example #9</p>
<div>
<pre>def detect_date(e):
 if is_date(e): return True
 for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
 if isinstance(e, date_type): return True
 # Slow!!!
 # for date_format in DATE_FORMATS:
 # try:
 # if datetime.strptime(e, date_format):
 # return True
 # except:
 # continue
 # Also slow
 # try: 
 # dparser.parse(e)
 # return True
 # except: pass
 return False </pre>
</div>
<p>Example #10</p>
<div>
<pre>def testISOStrippedFormatStrip3(self):
 self.assertEqual(parse("20030925T1049"),
 datetime(2003, 9, 25, 10, 49, 0)) </pre>
</div>
<p>Example #11</p>
<div>
<pre>def testDateCommandFormatStrip4(self):
 self.assertEqual(parse("Thu 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #12</p>
<div>
<pre>def testDateCommandFormatStrip5(self):
 self.assertEqual(parse("Sep 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #13</p>
<div>
<pre>def testDateCommandFormatStrip6(self):
 self.assertEqual(parse("10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #14</p>
<div>
<pre>def testDateCommandFormatStrip7(self):
 self.assertEqual(parse("10:36", default=self.default),
 datetime(2003, 9, 25, 10, 36)) </pre>
</div>
<p>Example #15</p>
<div>
<pre>def testDateCommandFormatStrip1(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 2003"),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #16</p>
<div>
<pre>def testISOStrippedFormatStrip5(self):
 self.assertEqual(parse("20030925"),
 datetime(2003, 9, 25)) </pre>
</div>
<p>Example #17</p>
<div>
<pre>def testISOStrippedFormatStrip4(self):
 self.assertEqual(parse("20030925T10"),
 datetime(2003, 9, 25, 10)) </pre>
</div>
<p>Example #18</p>
<div>
<pre>def testPythonLoggerFormat(self):
 self.assertEqual(parse("2003-09-25 10:49:41,502"),
 datetime(2003, 9, 25, 10, 49, 41, 502000)) </pre>
</div>
<p>Example #19</p>
<div>
<pre>def testISOStrippedFormatStrip1(self):
 self.assertEqual(parse("20030925T104941-0300"),
 datetime(2003, 9, 25, 10, 49, 41,
 tzinfo=self.brsttz)) </pre>
</div>
<p>Example #20</p>
<div>
<pre>def testDateCommandFormatStrip2(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #21</p>
<div>
<pre>def testDateCommandFormatStrip11(self):
 self.assertEqual(parse("Sep", default=self.default),
 datetime(2003, 9, 25)) </pre>
</div>
<p>Example #22</p>
<div>
<pre>def testDateCommandFormatIgnoreTz(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 ignoretz=True),
 datetime(2003, 9, 25, 10, 36, 28)) </pre>
</div>
<p>Example #23</p>
<div>
<pre>def testDateCommandFormatWithLong(self):
 if not PY3:
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 tzinfos={"BRST": long(-10800)}),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) </pre>
</div>
<p>Example #24</p>
<div>
<pre>def testDateCommandFormatReversed(self):
 self.assertEqual(parse("2003 10:36:28 BRST 25 Sep Thu",
 tzinfos=self.tzinfos),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) </pre>
</div>
<p>Example #25</p>
<div>
<pre>def testDateCommandFormat(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 tzinfos=self.tzinfos),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) </pre>
</div>
<p>Example #26</p>
<div>
<pre>def testParseWithNulls(self):
 # This relies on the from __future__ import unicode_literals, because
 # explicitly specifying a unicode literal is a syntax error in Py 3.2
 # May want to switch to u'...' if we ever drop Python 3.2 support.
 pstring = '\x00\x00August 29, 1924'
 self.assertEqual(parse(pstring),
 datetime(1924, 8, 29)) </pre>
</div>
<p>Example #27</p>
<div>
<pre>def testParserParseStr(self):
 from dateutil.parser import parser
 self.assertEqual(parser().parse(self.str_str),
 parser().parse(self.uni_str)) </pre>
</div>
<p>Example #28</p>
<div>
<pre>def testParseBytearray(self):
 # GH #417
 self.assertEqual(parse(bytearray(b'2014 January 19')),
 datetime(2014, 1, 19)) </pre>
</div>
<p>Example #29</p>
<div>
<pre>def testParseStr(self):
 self.assertEqual(parse(self.str_str),
 parse(self.uni_str)) </pre>
</div>
<p>Example #30</p>
<div>
<pre>def testParseStream(self):
 dstr = StringIO('2014 January 19')
 self.assertEqual(parse(dstr), datetime(2014, 1, 19)) </pre>
</div>
</div></div>||||I|||| * Search by Module
 * Search by Words
 * Search Projects
 Most Popular
 Top Python APIs Popular Projects
 * Java
 * Python
 * JavaScript
 * TypeScript
 * C++
 * Scala
 * Blog
 More from dateutil.parser
 * .add_argument()
 * .parse_args()
 * ._parsetz()
 * .parse()
 * .isoparse()
 * .add_mutually_exclusive_group()
 * .error()
 * .parserinfo()
 Related Methods
 * sys.exit()
 * sys.argv()
 * re.compile()
 * os.environ()
 * time.time()
 * datetime.datetime()
 * re.sub()
 * time.sleep()
 * re.search()
 * re.match()
 * os.makedirs()
 * logging.getLogger()
 * logging.DEBUG
 * datetime.timedelta()
 * json.loads()
 * json.dumps()
 * json.load()
 * argparse.ArgumentParser()
 * requests.get()
 * datetime.datetime.now()
 Related Modules
 * os
 * sys
 * re
 * time
 * logging
 * datetime
 * random
 * subprocess
 * copy
 * json
 * collections
 * functools
 * io
 * requests
 * datetime.datetime

 Python dateutil.parser.parse() Examples

 The following are 30 code examples of dateutil.parser.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dateutil.parser , or try the search function .
 Example #1
 Source File: __init__.py From aegea with Apache License 2.0 9 votes 
 
 def __new__(cls, t, snap=0):
 if isinstance(t, (str, bytes)) and t.isdigit():
 t = int(t)
 if not isinstance(t, (str, bytes)):
 from dateutil.tz import tzutc
 return datetime.fromtimestamp(t // 1000, tz=tzutc())
 try:
 units = ["weeks", "days", "hours", "minutes", "seconds"]
 diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
 if len(diffs) == 1:
 # Snap > 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
 snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
 snap_units.pop("day", None)
 snap_units.update(microsecond=0)
 ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
 cls._precision[ts] = snap_units
 return ts
 return dateutil_parse(t)
 except (ValueError, OverflowError, AssertionError):
 raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t)) 
 Example #2
 Source File: helpers.py From figures with MIT License 6 votes 
 
 def as_date(val):
 '''Casts the value to a ``datetime.date`` object if possible
 
 Else raises ``TypeError``
 '''
 # Important to check if datetime first because datetime.date objects
 # pass the isinstance(obj, datetime.date) test
 if isinstance(val, datetime.datetime):
 return val.date()
 elif isinstance(val, datetime.date):
 return val
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).date()
 else:
 raise TypeError(
 'date cannot be of type "{}".'.format(type(val)) +
 ' It must be able to be cast to a datetime.date') 
 Example #3
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 6 votes 
 
 def test_ybd(self):
 # If we have a 4-digit year, a non-numeric month (abbreviated or not),
 # and a day (1 or 2 digits), then there is no ambiguity as to which
 # token is a year/month/day. This holds regardless of what order the
 # terms are in and for each of the separators below.
 
 seps = ['-', ' ', '/', '.']
 
 year_tokens = ['%Y']
 month_tokens = ['%b', '%B']
 day_tokens = ['%d']
 if PLATFORM_HAS_DASH_D:
 day_tokens.append('%-d')
 
 prods = itertools.product(year_tokens, month_tokens, day_tokens)
 perms = [y for x in prods for y in itertools.permutations(x)]
 unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]
 
 actual = datetime(2003, 9, 25)
 
 for fmt in unambig_fmts:
 dstr = actual.strftime(fmt)
 res = parse(dstr)
 self.assertEqual(res, actual) 
 Example #4
 Source File: test_course_enrollment_view.py From figures with MIT License 6 votes 
 
 def test_get_course_enrollments(self, query_params, filter_args):
 expected_data = CourseEnrollment.objects.filter(**filter_args)
 request = APIRequestFactory().get(self.request_path + query_params)
 force_authenticate(request, user=self.staff_user)
 view = self. view_class.as_view({'get': 'list'})
 response = view(request)
 
 assert response.status_code == 200
 assert set(response.data.keys()) == set(
 ['count', 'next', 'previous', 'results',])
 
 assert len(response.data['results']) == len(expected_data)
 
 for data in response.data['results']:
 db_rec = expected_data.get(id=data['id'])
 assert parse(data['created']) == db_rec.created 
 Example #5
 Source File: helpers.py From figures with MIT License 6 votes 
 
 def as_datetime(val):
 '''
 TODO: Add arg flag to say if caller wants end of day, beginning of day
 or a particular time of day if the param is a datetime.date obj
 '''
 if isinstance(val, datetime.datetime):
 return val
 elif isinstance(val, datetime.date):
 # Return the end of the day, set timezone to be UTC
 return datetime.datetime(
 year=val.year,
 month=val.month,
 day=val.day,
 ).replace(tzinfo=utc)
 
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).replace(tzinfo=utc)
 else:
 raise TypeError(
 'value of type "{}" cannot be converted to a datetime object'.format(
 type(val))) 
 Example #6
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 6 votes 
 
 def testParseUnicodeWords(self):
 
 class rus_parserinfo(parserinfo):
 MONTHS = [("янв", "Январь"),
 ("фев", "Февраль"),
 ("мар", "Март"),
 ("апр", "Апрель"),
 ("май", "Май"),
 ("июн", "Июнь"),
 ("июл", "Июль"),
 ("авг", "Август"),
 ("сен", "Сентябрь"),
 ("окт", "Октябрь"),
 ("ноя", "Ноябрь"),
 ("дек", "Декабрь")]
 
 self.assertEqual(parse('10 Сентябрь 2015 10:20',
 parserinfo=rus_parserinfo()),
 datetime(2015, 9, 10, 10, 20)) 
 Example #7
 Source File: api_client.py From faxplus-python with MIT License 6 votes 
 
 def __deserialize_date(self, string):
 """Deserializes string to date.
 
 :param string: str.
 :return: date.
 """
 try:
 from dateutil.parser import parse
 return parse(string).date()
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason="Failed to parse `{0}` as date object".format(string)
 ) 
 Example #8
 Source File: api_client.py From faxplus-python with MIT License 6 votes 
 
 def __deserialize_datatime(self, string):
 """Deserializes string to datetime.
 
 The string should be in iso8601 datetime format.
 
 :param string: str.
 :return: datetime.
 """
 try:
 from dateutil.parser import parse
 return parse(string)
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason=(
 "Failed to parse `{0}` as datetime object"
 .format(string)
 )
 ) 
 Example #9
 Source File: type_detection.py From sato with Apache License 2.0 6 votes 
 
 def detect_date(e):
 if is_date(e): return True
 for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
 if isinstance(e, date_type): return True
 
 # Slow!!!
 # for date_format in DATE_FORMATS:
 # try:
 # if datetime.strptime(e, date_format):
 # return True
 # except:
 # continue
 
 # Also slow
 # try: 
 # dparser.parse(e)
 # return True
 # except: pass
 return False 
 Example #10
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testISOStrippedFormatStrip3(self):
 self.assertEqual(parse("20030925T1049"),
 datetime(2003, 9, 25, 10, 49, 0)) 
 Example #11
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip4(self):
 self.assertEqual(parse("Thu 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
 Example #12
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip5(self):
 self.assertEqual(parse("Sep 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
 Example #13
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip6(self):
 self.assertEqual(parse("10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
 Example #14
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip7(self):
 self.assertEqual(parse("10:36", default=self.default),
 datetime(2003, 9, 25, 10, 36)) 
 Example #15
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip1(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 2003"),
 datetime(2003, 9, 25, 10, 36, 28)) 
 Example #16
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testISOStrippedFormatStrip5(self):
 self.assertEqual(parse("20030925"),
  datetime(2003, 9, 25)) 
 Example #17
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testISOStrippedFormatStrip4(self):
 self.assertEqual(parse("20030925T10"),
  datetime(2003, 9, 25, 10)) 
 Example #18
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testPythonLoggerFormat(self):
 self.assertEqual(parse("2003-09-25 10:49:41,502"),
  datetime(2003, 9, 25, 10, 49, 41, 502000)) 
 Example #19
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testISOStrippedFormatStrip1(self):
 self.assertEqual(parse("20030925T104941-0300"),
  datetime(2003, 9, 25, 10, 49, 41,
  tzinfo=self.brsttz)) 
 Example #20
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip2(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28", default=self.default),
  datetime(2003, 9, 25, 10, 36, 28)) 
 Example #21
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatStrip11(self):
 self.assertEqual(parse("Sep", default=self.default),
  datetime(2003, 9, 25)) 
 Example #22
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatIgnoreTz(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
  ignoretz=True),
  datetime(2003, 9, 25, 10, 36, 28)) 
 Example #23
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatWithLong(self):
 if not PY3:
  self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
  tzinfos={"BRST": long(-10800)}),
  datetime(2003, 9, 25, 10, 36, 28,
  tzinfo=self.brsttz)) 
 Example #24
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormatReversed(self):
 self.assertEqual(parse("2003 10:36:28 BRST 25 Sep Thu",
  tzinfos=self.tzinfos),
  datetime(2003, 9, 25, 10, 36, 28,
  tzinfo=self.brsttz)) 
 Example #25
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testDateCommandFormat(self):
  self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
  tzinfos=self.tzinfos),
  datetime(2003, 9, 25, 10, 36, 28,
  tzinfo=self.brsttz)) 
 Example #26
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testParseWithNulls(self):
  # This relies on the from __future__ import unicode_literals, because
  # explicitly specifying a unicode literal is a syntax error in Py 3.2
  # May want to switch to u'...' if we ever drop Python 3.2 support.
  pstring = '\x00\x00August 29, 1924'
 
  self.assertEqual(parse(pstring),
  datetime(1924, 8, 29)) 
 Example #27
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testParserParseStr(self):
  from dateutil.parser import parser
 
  self.assertEqual(parser().parse(self.str_str),
  parser().parse(self.uni_str)) 
 Example #28
 Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
 
 def testParseBytearray(self):
  # GH #417
  self.assertEqual(parse(bytearray(b'2014 January 19')),
  datetime(2014, 1, 19)) 
 Example #29
  Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
  
  def testParseStr(self):
  self.assertEqual(parse(self.str_str),
  parse(self.uni_str)) 
 Example #30
  Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 5 votes 
  
  def testParseStream(self):
  dstr = StringIO('2014 January 19')
  
  self.assertEqual(parse(dstr), datetime(2014, 1, 19)) 


The following are 
code examples of .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
, or try the search function
.
Example #1
def __new__(cls, t, snap=0):
 if isinstance(t, (str, bytes)) and t.isdigit():
 t = int(t)
 if not isinstance(t, (str, bytes)):
 from dateutil.tz import tzutc
 return datetime.fromtimestamp(t // 1000, tz=tzutc())
 try:
 units = ["weeks", "days", "hours", "minutes", "seconds"]
 diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
 if len(diffs) == 1:
 # Snap &gt; 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
 snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
 snap_units.pop("day", None)
 snap_units.update(microsecond=0)
 ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
 cls._precision[ts] = snap_units
 return ts
 return dateutil_parse(t)
 except (ValueError, OverflowError, AssertionError):
 raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t)) 
Example #2
def as_date(val):
 '''Casts the value to a ``datetime.date`` object if possible
 Else raises ``TypeError``
 '''
 # Important to check if datetime first because datetime.date objects
 # pass the isinstance(obj, datetime.date) test
 if isinstance(val, datetime.datetime):
 return val.date()
 elif isinstance(val, datetime.date):
 return val
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).date()
 else:
 raise TypeError(
 'date cannot be of type "{}".'.format(type(val)) +
 ' It must be able to be cast to a datetime.date') 
Example #3
def test_ybd(self):
 # If we have a 4-digit year, a non-numeric month (abbreviated or not),
 # and a day (1 or 2 digits), then there is no ambiguity as to which
 # token is a year/month/day. This holds regardless of what order the
 # terms are in and for each of the separators below.
 seps = ['-', ' ', '/', '.']
 year_tokens = ['%Y']
 month_tokens = ['%b', '%B']
 day_tokens = ['%d']
 if PLATFORM_HAS_DASH_D:
 day_tokens.append('%-d')
 prods = itertools.product(year_tokens, month_tokens, day_tokens)
 perms = [y for x in prods for y in itertools.permutations(x)]
 unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]
 actual = datetime(2003, 9, 25)
 for fmt in unambig_fmts:
 dstr = actual.strftime(fmt)
 res = parse(dstr)
 self.assertEqual(res, actual) 
Example #4
def test_get_course_enrollments(self, query_params, filter_args):
 expected_data = CourseEnrollment.objects.filter(**filter_args)
 request = APIRequestFactory().get(self.request_path + query_params)
 force_authenticate(request, user=self.staff_user)
 view = self. view_class.as_view({'get': 'list'})
 response = view(request)
 assert response.status_code == 200
 assert set(response.data.keys()) == set(
 ['count', 'next', 'previous', 'results',])
 assert len(response.data['results']) == len(expected_data)
 for data in response.data['results']:
 db_rec = expected_data.get(id=data['id'])
 assert parse(data['created']) == db_rec.created 
Example #5
def as_datetime(val):
 '''
 TODO: Add arg flag to say if caller wants end of day, beginning of day
 or a particular time of day if the param is a datetime.date obj
 '''
 if isinstance(val, datetime.datetime):
 return val
 elif isinstance(val, datetime.date):
 # Return the end of the day, set timezone to be UTC
 return datetime.datetime(
 year=val.year,
 month=val.month,
 day=val.day,
 ).replace(tzinfo=utc)
 elif isinstance(val, basestring): # noqa: F821
 return dateutil_parse(val).replace(tzinfo=utc)
 else:
 raise TypeError(
 'value of type "{}" cannot be converted to a datetime object'.format(
 type(val))) 
Example #6
def testParseUnicodeWords(self):
 class rus_parserinfo(parserinfo):
 MONTHS = [("янв", "Январь"),
 ("фев", "Февраль"),
 ("мар", "Март"),
 ("апр", "Апрель"),
 ("май", "Май"),
 ("июн", "Июнь"),
 ("июл", "Июль"),
 ("авг", "Август"),
 ("сен", "Сентябрь"),
 ("окт", "Октябрь"),
 ("ноя", "Ноябрь"),
 ("дек", "Декабрь")]
 self.assertEqual(parse('10 Сентябрь 2015 10:20',
 parserinfo=rus_parserinfo()),
 datetime(2015, 9, 10, 10, 20)) 
Example #7
def __deserialize_date(self, string):
 """Deserializes string to date.
 :param string: str.
 :return: date.
 """
 try:
 from dateutil.parser import parse
 return parse(string).date()
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason="Failed to parse `{0}` as date object".format(string)
 ) 
Example #8
def __deserialize_datatime(self, string):
 """Deserializes string to datetime.
 The string should be in iso8601 datetime format.
 :param string: str.
 :return: datetime.
 """
 try:
 from dateutil.parser import parse
 return parse(string)
 except ImportError:
 return string
 except ValueError:
 raise rest.ApiException(
 status=0,
 reason=(
 "Failed to parse `{0}` as datetime object"
 .format(string)
 )
 ) 
Example #9
def detect_date(e):
 if is_date(e): return True
 for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
 if isinstance(e, date_type): return True
 # Slow!!!
 # for date_format in DATE_FORMATS:
 # try:
 # if datetime.strptime(e, date_format):
 # return True
 # except:
 # continue
 # Also slow
 # try: 
 # dparser.parse(e)
 # return True
 # except: pass
 return False 
Example #10
def testISOStrippedFormatStrip3(self):
 self.assertEqual(parse("20030925T1049"),
 datetime(2003, 9, 25, 10, 49, 0)) 
Example #11
def testDateCommandFormatStrip4(self):
 self.assertEqual(parse("Thu 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #12
def testDateCommandFormatStrip5(self):
 self.assertEqual(parse("Sep 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #13
def testDateCommandFormatStrip6(self):
 self.assertEqual(parse("10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #14
def testDateCommandFormatStrip7(self):
 self.assertEqual(parse("10:36", default=self.default),
 datetime(2003, 9, 25, 10, 36)) 
Example #15
def testDateCommandFormatStrip1(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 2003"),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #16
def testISOStrippedFormatStrip5(self):
 self.assertEqual(parse("20030925"),
 datetime(2003, 9, 25)) 
Example #17
def testISOStrippedFormatStrip4(self):
 self.assertEqual(parse("20030925T10"),
 datetime(2003, 9, 25, 10)) 
Example #18
def testPythonLoggerFormat(self):
 self.assertEqual(parse("2003-09-25 10:49:41,502"),
 datetime(2003, 9, 25, 10, 49, 41, 502000)) 
Example #19
def testISOStrippedFormatStrip1(self):
 self.assertEqual(parse("20030925T104941-0300"),
 datetime(2003, 9, 25, 10, 49, 41,
 tzinfo=self.brsttz)) 
Example #20
def testDateCommandFormatStrip2(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28", default=self.default),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #21
def testDateCommandFormatStrip11(self):
 self.assertEqual(parse("Sep", default=self.default),
 datetime(2003, 9, 25)) 
Example #22
def testDateCommandFormatIgnoreTz(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 ignoretz=True),
 datetime(2003, 9, 25, 10, 36, 28)) 
Example #23
def testDateCommandFormatWithLong(self):
 if not PY3:
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 tzinfos={"BRST": long(-10800)}),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) 
Example #24
def testDateCommandFormatReversed(self):
 self.assertEqual(parse("2003 10:36:28 BRST 25 Sep Thu",
 tzinfos=self.tzinfos),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) 
Example #25
def testDateCommandFormat(self):
 self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
 tzinfos=self.tzinfos),
 datetime(2003, 9, 25, 10, 36, 28,
 tzinfo=self.brsttz)) 
Example #26
def testParseWithNulls(self):
 # This relies on the from __future__ import unicode_literals, because
 # explicitly specifying a unicode literal is a syntax error in Py 3.2
 # May want to switch to u'...' if we ever drop Python 3.2 support.
 pstring = '\x00\x00August 29, 1924'
 self.assertEqual(parse(pstring),
 datetime(1924, 8, 29)) 
Example #27
def testParserParseStr(self):
 from dateutil.parser import parser
 self.assertEqual(parser().parse(self.str_str),
 parser().parse(self.uni_str)) 
Example #28
def testParseBytearray(self):
 # GH #417
 self.assertEqual(parse(bytearray(b'2014 January 19')),
 datetime(2014, 1, 19)) 
Example #29
def testParseStr(self):
 self.assertEqual(parse(self.str_str),
 parse(self.uni_str)) 
Example #30
def testParseStream(self):
 dstr = StringIO('2014 January 19')
 self.assertEqual(parse(dstr), datetime(2014, 1, 19))
Python Examples of dateutil.parser.parse
https://www.programcreek.com/python/example/98372/dateutil.parser.parse
https://stackoverflow.com/questions/45988363/getting-timezone-from-dateutil-parser-parse-in-python
Getting timezone from dateutil.parser.parse in Python
2023-01-02
Frazman Frazman
<div><div>
<p>From the <a href="https://docs.python.org/library/datetime.html?highlight=utcoffset#datetime.datetime.utcoffset">datetime docs</a>:</p>
<blockquote>
 <p>If tzinfo is None, returns None</p>
</blockquote>
<p>In your code, <code>dt.tzinfo</code> is <code>None</code>, so the timezone information was not parsed by <code>parse_date</code> into the <code>dt</code>. Your datetime <code>dt</code> is "naive" (has no timezone information).</p>
<p>As per the <a href="http://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse">dateutil docs</a>, You can pass your own timezone information to <code>parse_date</code> as either a <code>tzoffset</code> or <code>tzfile</code>:</p>
<pre><code>tzinfos = {"CDT": -21600}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzoffset('CDT', -21600)
from dateutil import tz
tzinfos = {"CDT": tz.gettz('US/Central')}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzfile('/usr/share/zoneinfo/US/Central')
</code></pre>
<p>Or you can encode the timezone offset into the string:</p>
<pre><code>dt = parse_date('2017-08-28 06:08:20-06:00')
dt.tzinfo #tzoffset(None, -21600)
</code></pre>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 Getting timezone from dateutil.parser.parse in Python

 Ask Question
 Asked 5 years, 6 months ago
 Modified 1 month ago
 Viewed 14k times
 6

 Trying to parse the datetime string with timezone info and get the utc offset

 from dateutil.parser import parse as parse_date
 s = '2017-08-28 06:08:20,488 CDT'
 dt = parse_date(s)
 print(dt.utcoffset()) # prints `None`
 

 Why is utcoffset returning None rather than -5 as offset?

 * python
 * datetime
 * timezone
 * python-dateutil
 Share
 Follow
 edited Jan 2 at 19:48
 FObersteiner
 20.5k 6 6 gold badges 35 35 silver badges 62 62 bronze badges
 asked Aug 31, 2017 at 18:58
 frazman frazman
 31.5k 70 70 gold badges 179 179 silver badges 266 266 bronze badges
 0
 Add a comment |

 1 Answer

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 12

 From the datetime docs:

 If tzinfo is None, returns None

 In your code, dt.tzinfo is None, so the timezone information was not parsed by parse_date into the dt. Your datetime dt is "naive" (has no timezone information).

 As per the dateutil docs, You can pass your own timezone information to parse_date as either a tzoffset or tzfile:

 tzinfos = {"CDT": -21600}
 dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
 dt.tzinfo #tzoffset('CDT', -21600)
 
 from dateutil import tz
 tzinfos = {"CDT": tz.gettz('US/Central')}
 dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
 dt.tzinfo #tzfile('/usr/share/zoneinfo/US/Central')
 

 Or you can encode the timezone offset into the string:

 dt = parse_date('2017-08-28 06:08:20-06:00')
 dt.tzinfo #tzoffset(None, -21600)
 
 Share
 Follow
 edited Jun 11, 2020 at 11:35
 phoenix
 7,438 5 5 gold badges 37 37 silver badges 44 44 bronze badges
 answered Aug 31, 2017 at 21:14
 TheoretiCAL TheoretiCAL
 18.7k 8 8 gold badges 40 40 silver badges 64 64 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * datetime
 * timezone
 * python-dateutil
 or ask your own question.

 * The Overflow Blog
 * ML and AI consulting-as-a-service (Ep. 541)
 * Why governments need open source more than ever
 * Featured on Meta
 * Ticket smash for [status-review] tag: Part Deux
 * We've added a "Necessary cookies only" option to the cookie consent popup
 * The [amazon] tag is being burninated
 * Microsoft Azure Collective launch and proposed tag changes
 * Temporary policy: ChatGPT is banned

 Linked

 0
 Generating a Python datetime from String

 Related

 7136
 What are metaclasses in Python?
 7646
 Does Python have a ternary conditional operator?
 3244
 How do I concatenate two lists in Python?
 3055
 Manually raising (throwing) an exception in Python
 3588
 Does Python have a string 'contains' substring method?
 3007
 How can I access environment variables in Python?
 757
 How to make a timezone aware datetime object
 2746
 How can I remove a key from a Python dictionary?
 246
 Format date in a specific timezone

 Hot Network Questions

 * Definite integrals with equal limits
 * Expedia charged my card even though the "Reserve Now, Pay At Property" option was selected
 * Why do heating curves have plateaus?
 * At what technological level can a mixed-gender military not be at a disadvantage to an all-male one?
 * "Expect" Nature publication for PhD?
 * A Queen and her Pawns
 * You don't use a comma listing only two items, but SAT Reading Passage does. Why?
 * Clear and concrete definition of "Third World"
 * How do gas turbine engines and turbofan engines keep constant compressor side rpm?
 * Can a private person deceive a defendant to obtain evidence?
 * Discrete N-channel-MOSFET driver switching circuit with NPN and PNP transistor
 * In Ephesians 1:7, whose blood, the Son’s or the Father’s?
 * How does one go about learning to program a new micro controller?
 * Does the pro rate rule on taxes for backdoor Roth IRA conversion apply if you have multiple Roth NOT traditional IRAs?
 * Short story featuring a detective and his alien sidekick
 * Can a VGA monitor be connected to parallel port?
 * How can you achieve decent clock accuracy in microcontrollers (e.g., max 1 second drift in a year)? How do digital watch manufacturers accomplish it?
 * ddrescue: How to restart from pass 1?
 * article usage, He invented THE slide rule
 * In quantum field theory, why is vacuum considered to have the same properties as a particle?
 * Identify and split data in other languages using QGIS
 * Potential and Field
 * Sci fi book about a character with an implant/enhanced capabilities who was hired to assassinate a member of elite society
 * Does the discount from Mindsplice Apparatus apply to flashback costs?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.24.43259

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Necessary cookies only
 Customize settings
From the datetime docs:
 If tzinfo is None, returns None
In your code, dt.tzinfo is None, so the timezone information was not parsed by parse_date into the dt. Your datetime dt is "naive" (has no timezone information).
As per the dateutil docs, You can pass your own timezone information to parse_date as either a tzoffset or tzfile:
 tzinfos = {"CDT": -21600}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzoffset('CDT', -21600)
from dateutil import tz
tzinfos = {"CDT": tz.gettz('US/Central')}
dt = parse_date('2017-08-28 06:08:20 CDT', tzinfos=tzinfos)
dt.tzinfo #tzfile('/usr/share/zoneinfo/US/Central')
 
Or you can encode the timezone offset into the string:
 dt = parse_date('2017-08-28 06:08:20-06:00')
dt.tzinfo #tzoffset(None, -21600)
Getting timezone from dateutil.parser.parse in Python
https://stackoverflow.com/questions/45988363/getting-timezone-from-dateutil-parser-parse-in-python
https://stackoverflow.com/questions/65338201/parse-date-string-to-datetime-with-timezone
Parse Date string to datetime with timezone
2020-12-18
Aman Jain Aman Jain
<div><div>
<p>Using <code>dateutil.parser</code> you can directly parse your date correctly.</p>
<p>Note that <code>CST</code> is an ambiguous timezone, so you need to specify which one you mean. You can either do this directly in the <code>tzinfos</code> parameter of the <code>parse()</code> call or you can define a dictionary that has mappings for timezones and pass this. In this dict, you can either specify the offset, e.g.</p>
<pre><code>timezone_info = {
 : - * ,
 : * ,
 : * 
}
parser.parse(r, tzinfos=timezone_info)
</code></pre>
<p>or (using <code>gettz</code>) directly specify a timezone:</p>
<pre><code>timezone_info = {
 : gettz(),
 : gettz(),
 : gettz()
}
parser.parse(r, tzinfos=timezone_info)
</code></pre>
<p>See also the <a href="https://dateutil.readthedocs.io/en/stable/parser.html">dateutil.parser documentation</a> and the answers to <a href="https://stackoverflow.com/q/51206500/14015737">this SO question</a>.</p>
<p>Be aware that the latter approach is tricky if you have a location with daylight saving time! Depending on the date you apply it to, <code>gettz("America/Chicago")</code> will have UTC-5 or UTC-6 as a result (as Chicago switches between Central Standard Time and Central Daylight Time). So depending on your input data, the second example may actually not really be correct and yield the wrong outcome! Currently, China observes China Standard Time (CST) all year, so for your use case it makes no difference (may depend on your date range though).</p>
<p>Overall:</p>
<pre><code> dateutil parser
 dateutil.tz gettz
timezone_info = {: gettz()}
r = 
d = parser.parse(r, tzinfos=timezone_info)
(d)
(d.strftime())
</code></pre>
<p>gets you</p>
<pre><code>-- 08::+08:
-- 08:: CST+0800
</code></pre>
<p><strong>EDIT</strong>: Printing the human readable timezone name instead of the abbreviated one name is just a little more complicated with this approach, as <code>dateutil.tz.gettz()</code> gets you a <code>tzfile</code> that has no attribute which has just the name. However, you can obtain it via the protected <code>_filename</code> using <code>split()</code>:</p>
<pre><code>(d.strftime() + + .join(d.tzinfo._filename.split()[-:]))
</code></pre>
<p>yields</p>
<pre><code>-- 08::+08: Asia/Shanghai
</code></pre>
<p>This of course only works if you used <code>gettz()</code> to set the timezone in the first place.</p>
<p><strong>EDIT 2</strong>: If you <em>know</em> that all your dates are in CST anyway, you can also ignore the timezone when parsing. This gets you naive (or unanware) datetimes which you can then later add a human readable timezone to. You can do this using <code>replace()</code> and specify the timezone either as shown above using <code>gettz()</code> or using <code>timezone(()</code> from the <code>pytz</code> module:</p>
<pre><code> dateutil parser
 dateutil.tz gettz
 pytz
r = 
d = parser.parse(r, ignoretz=)
d_dateutil = d.replace(tzinfo=gettz())
d_pytz = d.replace(tzinfo=pytz.timezone())
</code></pre>
<p>Note that depending on which module you use to add the timezone information, the class of <code>tzinfo</code> differs. For the <code>pytz</code> object, there is a more direct way of accessing the timezone in human readable form:</p>
<pre><code>((d_dateutil.tzinfo))
(.join(d_dateutil.tzinfo._filename.split()[-:]))
((d_pytz.tzinfo))
(d_pytz.tzinfo.zone)
</code></pre>
<p>produces</p>
<pre><code>&lt; &gt;
Asia/Shanghai
&lt; &gt;
Asia/Shanghai
</code></pre>
</div></div>||||I|||| Join Stack Overflow

 By clicking “Sign up”, you agree to our terms of service and acknowledge you have read our privacy policy.

 Sign up with Google
 Sign up with GitHub

 OR

 Email
 Password
 Sign up

 Already have an account? Log in
Skip to main content
 Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. Labs The future of collective knowledge sharing
 6. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. 
 1. Home
 2. Questions
 3. Tags
 4. 
 5. Users
 6. Companies
 7. Labs
 8. Discussions
 9. Collectives

 10. Communities for your favorite technologies. Explore all Collectives

 2. Teams

 Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

 Explore Teams Create a free Team
 3. Teams

 4. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 Get early access and see previews of new features.

 Learn more about Labs

 Parse Date string to datetime with timezone

 Ask Question
 Asked 3 years, 4 months ago
 Modified 3 years, 1 month ago
 Viewed 4k times
 This question shows research effort; it is useful and clear
 3
 Save this question.
 Show activity on this post.

 I have a string:

 r = 'Thu Dec 17 08:56:41 CST 2020'
 

 Here CST represent China central time('Asia/Shanghai'). I wanted to parse it to datetime...I am doing something like

 from dateparser import parse
 r1 = parse(r)
 

 Which is giving me r1 as:

 2020-12-17 08:56:41-06:00
 

 And I am also doing this

 r2 = r1.replace(tzinfo=pytz.timezone("Asia/Shanghai"))
 

 And this is giving me r2 as:

 2020-12-17 08:50:41+08:00
 

 There is 6 min lag in r2 can someone tell me why is that? And how to correctly transfer my raw string r1 to desired r2 which is:

 2020-12-17 08:56:41 in Asia/Shanghai timezone
 

 Thanks

 * python
 * datetime
 * date-parsing
 Share
 Share a link to this question
 Copy linkCC BY-SA 4.0
 Improve this question
 Follow
 Follow this question to receive notifications
 edited Dec 18, 2020 at 16:53
 buddemat
 5,093 14 14 gold badges 32 32 silver badges 53 53 bronze badges
 asked Dec 17, 2020 at 9:45
 aman jain aman jain
 63 1 1 silver badge 8 8 bronze badges
 1
 * related: stackoverflow.com/q/65263556/10197418 (one of many...)
 – FObersteiner
 Dec 17, 2020 at 14:35
 Add a comment |

 2 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 This answer is useful
 5
 Save this answer.
 Show activity on this post.

 Using dateutil.parser you can directly parse your date correctly.

 Note that CST is an ambiguous timezone, so you need to specify which one you mean. You can either do this directly in the tzinfos parameter of the parse() call or you can define a dictionary that has mappings for timezones and pass this. In this dict, you can either specify the offset, e.g.

 timezone_info = {
 "CDT": -5 * 3600,
 "CEST": 2 * 3600,
 "CST": 8 * 3600
 }
 
 parser.parse(r, tzinfos=timezone_info)
 

 or (using gettz) directly specify a timezone:

 timezone_info = {
 "CDT": gettz("America/Chicago"),
 "CEST": gettz("Europe/Berlin"),
 "CST": gettz("Asia/Shanghai")
 }
 
 parser.parse(r, tzinfos=timezone_info)
 

 See also the dateutil.parser documentation and the answers to this SO question.

 Be aware that the latter approach is tricky if you have a location with daylight saving time! Depending on the date you apply it to, gettz("America/Chicago") will have UTC-5 or UTC-6 as a result (as Chicago switches between Central Standard Time and Central Daylight Time). So depending on your input data, the second example may actually not really be correct and yield the wrong outcome! Currently, China observes China Standard Time (CST) all year, so for your use case it makes no difference (may depend on your date range though).

 Overall:

 from dateutil import parser
 from dateutil.tz import gettz
 
 timezone_info = {"CST": gettz("Asia/Shanghai")}
 
 r = 'Thu Dec 17 08:56:41 CST 2020'
 d = parser.parse(r, tzinfos=timezone_info)
 
 print(d)
 print(d.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
 

 gets you

 2020-12-17 08:56:41+08:00
 2020-12-17 08:56:41 CST+0800
 

 EDIT: Printing the human readable timezone name instead of the abbreviated one name is just a little more complicated with this approach, as dateutil.tz.gettz() gets you a tzfile that has no attribute which has just the name. However, you can obtain it via the protected _filename using split():

 print(d.strftime('%Y-%m-%d %H:%M:%S') + " in " + "/".join(d.tzinfo._filename.split('/')[-2:]))
 

 yields

 2020-12-17 08:56:41+08:00 in Asia/Shanghai
 

 This of course only works if you used gettz() to set the timezone in the first place.

 EDIT 2: If you know that all your dates are in CST anyway, you can also ignore the timezone when parsing. This gets you naive (or unanware) datetimes which you can then later add a human readable timezone to. You can do this using replace() and specify the timezone either as shown above using gettz() or using timezone(() from the pytz module:

 from dateutil import parser
 from dateutil.tz import gettz
 import pytz
 
 r = 'Thu Dec 17 08:56:41 CST 2020'
 d = parser.parse(r, ignoretz=True)
 
 d_dateutil = d.replace(tzinfo=gettz('Asia/Shanghai'))
 d_pytz = d.replace(tzinfo=pytz.timezone('Asia/Shanghai'))
 

 Note that depending on which module you use to add the timezone information, the class of tzinfo differs. For the pytz object, there is a more direct way of accessing the timezone in human readable form:

 print(type(d_dateutil.tzinfo))
 print("/".join(d_dateutil.tzinfo._filename.split('/')[-2:]))
 
 print(type(d_pytz.tzinfo))
 print(d_pytz.tzinfo.zone)
 
 

 produces

 <class 'dateutil.tz.tz.tzfile'>
 Asia/Shanghai
 <class 'pytz.tzfile.Asia/Shanghai'>
 Asia/Shanghai
 
 Share
 Share a link to this answer
 Copy linkCC BY-SA 4.0
 Improve this answer
 Follow
 Follow this answer to receive notifications
 edited Mar 13, 2021 at 9:33
 answered Dec 17, 2020 at 11:06
 buddemat buddemat
 5,093 14 14 gold badges 32 32 silver badges 53 53 bronze badges
 Add a comment |
 This answer is useful
 2
 Save this answer.
 Show activity on this post.
 from datetime import datetime
 import pytz
 
 # The datetime string you have
 r = "Thu Dec 17 08:56:41 CST 2020"
 
 # The time-zone string you want to use
 offset_string = 'Asia/Shanghai'
 
 # convert the time zone string into offset from UTC
 # a. datetime.now(pytz.timezone(offset_string)).utcoffset().total_seconds() --- returns seconds offset from UTC
 # b. convert seconds into hours (decimal) --- divide by 60 twice
 # c. remove the decimal point, we want the structure as: +0800
 offset_num_repr = '+{:05.2f}'.format(datetime.now(pytz.timezone(offset_string)).utcoffset().total_seconds()/60/60).replace('.', '')
 print('Numeric representation of the offset: ', offset_num_repr)
 
 # replace the CST 2020 with numeric timezone offset
 # a. replace it with the offset computed above
 updated_datetime = str(r).replace('CST', offset_num_repr)
 print('\t Modified datetime string: ', updated_datetime)
 
 # Now parse your string into datetime object
 r = datetime.strptime(updated_datetime, "%a %b %d %H:%M:%S %z %Y")
 print('\tFinal parsed datetime object: ', r)
 
 

 Should produce:

 Numeric representation of the offset: +0800
 Modified datetime string: Thu Dec 17 08:56:41 +0800 2020
 Final parsed datetime object: 2020-12-17 08:56:41+08:00
 
 Share
 Share a link to this answer
 Copy linkCC BY-SA 4.0
 Improve this answer
 Follow
 Follow this answer to receive notifications
 edited Dec 18, 2020 at 6:20
 answered Dec 17, 2020 at 11:11
 anurag anurag
 1,805 1 1 gold badge 10 10 silver badges 32 32 bronze badges
 Add a comment |

 Your Answer

 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 

 Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

 Not the answer you're looking for? Browse other questions tagged
 * python
 * datetime
 * date-parsing
 or ask your own question.

 * The Overflow Blog
 * Supporting the world’s most-used database engine through 2050
 * Net neutrality is in; TikTok and noncompetes are out
 * Featured on Meta
 * Testing a new version of Stack Overflow Jobs
 * Pausing the 1-rep voting experiment on Stack Overflow: reflecting on the...
 * Temporary policy: Generative AI (e.g., ChatGPT) is banned

 Linked

 17
 how to convert a string datetime with unknown timezone to timestamp in python
 2
 How to create multiple pandas dataframe columns based on multiple lines in a cell, across every rows?
 0
 Convert EST, CST and DST timezones to unix timestamp in Pytz Module in Python 3

 Related

 1
 How do I parse timezones from dates in python
 8
 Correctly parse date string with timezone information
 2
 Parse string with date and timezone to UTC datetime
 1
 Python time zone parsing
 2
 Python parse datestring to date
 2
 Parsing Datetime in Python with timezone
 0
 Parse a Date in Python with datetime
 0
 Parsing time to Datetime with Timezone
 0
 How to convert date string with timezone to datetime in python
 1
 Parsing a string with time zone given as a string

 Hot Network Questions

 * Horror/Monster movie shown on TV in Basic Instinct
 * Why is COALESCE not a function?
 * How would I make text bend (as if it's being folded) but not on an isometric grid?
 * Inner voice when reading mathematics
 * Is it idiomatic to say "I have to race with time" to mean I have to do a thing very fast and finish it before something bad might happen?
 * Can a pilot tell a controller they don't need IFR clearance?
 * Reverse rollover IRA and rule of 55
 * How to obtain meat when you have no hunters in the colony?
 * Why is construction required in geometry?
 * What are the claimed instances of contradictions and omissions in the Bible the Church of Jesus Christ of Latter-day Saints has identified?
 * Limit of integral of sum of cosine functions by CLT?
 * What would you call the ground floor if you were in a country where it is the first floor?
 * Does Sola Scriptura imply that one should expect no personal spiritual experience of the Gospel?
 * How to have italicized double-storey "a"?
 * Is there a true 1 dimensional object?
 * Do multi-acceptance/multi-language automata exist in literature?
 * How to obtain the list of outermost graph nodes
 * What to check when chainsaw chain won't move freely?
 * Divisibility patterns
 * What idiom could describe bureaucratic inefficiency?
 * Restrict User in an AD group from logging on to computers but allow them to use their windows credentials to log on to a webapp
 * Sort a file by lines, regardless of their content
 * Does weight of an aircraft affect its ability to pull G?
 * Etymology of ダンボール
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2024.4.30.8420

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
 Accept all cookies Necessary cookies only
 Customize settings
Using dateutil.parser you can directly parse your date correctly.
Note that CST is an ambiguous timezone, so you need to specify which one you mean. You can either do this directly in the tzinfos parameter of the parse() call or you can define a dictionary that has mappings for timezones and pass this. In this dict, you can either specify the offset, e.g.
 timezone_info = {
 : - * ,
 : * ,
 : * 
}
parser.parse(r, tzinfos=timezone_info)
 
or (using gettz) directly specify a timezone:
 timezone_info = {
 : gettz(),
 : gettz(),
 : gettz()
}
parser.parse(r, tzinfos=timezone_info)
 
See also the dateutil.parser documentation and the answers to this SO question.
Be aware that the latter approach is tricky if you have a location with daylight saving time! Depending on the date you apply it to, gettz("America/Chicago") will have UTC-5 or UTC-6 as a result (as Chicago switches between Central Standard Time and Central Daylight Time). So depending on your input data, the second example may actually not really be correct and yield the wrong outcome! Currently, China observes China Standard Time (CST) all year, so for your use case it makes no difference (may depend on your date range though).
Overall:
  dateutil parser
 dateutil.tz gettz
timezone_info = {: gettz()}
r = 
d = parser.parse(r, tzinfos=timezone_info)
(d)
(d.strftime())
 
gets you
 -- 08::+08:
-- 08:: CST+0800
 
 EDIT: Printing the human readable timezone name instead of the abbreviated one name is just a little more complicated with this approach, as dateutil.tz.gettz() gets you a tzfile that has no attribute which has just the name. However, you can obtain it via the protected _filename using split():
 (d.strftime() + + .join(d.tzinfo._filename.split()[-:]))
 
yields
 -- 08::+08: Asia/Shanghai
 
This of course only works if you used gettz() to set the timezone in the first place.
 EDIT 2: If you know that all your dates are in CST anyway, you can also ignore the timezone when parsing. This gets you naive (or unanware) datetimes which you can then later add a human readable timezone to. You can do this using replace() and specify the timezone either as shown above using gettz() or using timezone(() from the pytz module:
  dateutil parser
 dateutil.tz gettz
 pytz
r = 
d = parser.parse(r, ignoretz=)
d_dateutil = d.replace(tzinfo=gettz())
d_pytz = d.replace(tzinfo=pytz.timezone())
 
Note that depending on which module you use to add the timezone information, the class of tzinfo differs. For the pytz object, there is a more direct way of accessing the timezone in human readable form:
 ((d_dateutil.tzinfo))
(.join(d_dateutil.tzinfo._filename.split()[-:]))
((d_pytz.tzinfo))
(d_pytz.tzinfo.zone)
 
produces
 &lt; &gt;
Asia/Shanghai
&lt; &gt;
Asia/Shanghai
Parse Date string to datetime with timezone
https://stackoverflow.com/questions/65338201/parse-date-string-to-datetime-with-timezone
https://stackoverflow.com/questions/53450395/change-timestamp-from-dateutil-from-utc-to-not-utc
Change timestamp from dateutil from utc to not utc
2018-11-23
Gamsner Gamsner
<div><div>
<p>The <code>astimezone()</code> method shown by Paul will adjust the date and time to match the new timezone. <strong>This is usually what you want.</strong> For example, if the timestamp you have is UTC, and you want to convert it to UTC+1 (or any other timezone), then you need to add an hour (or do some other arithmetic), which <code>astimezone()</code> does for you. It also takes care of daylight saving time or summer time, as well as numerous <a href="https://www.bbc.com/news/world-asia-16351377">more substantial</a> timezone irregularities.</p>
<p>However, sometimes this is not what you want. For example, if you have a UTC+1 timezone which is incorrectly labeled as UTC, then <code>astimezone()</code> will add an hour, producing a UTC+2 datetime which is incorrectly labeled UTC+1. If that describes your problem, then you should use the <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.replace"><code>replace()</code></a> method instead of <code>astimezone()</code>. This will simply "relabel" the timezone without doing any conversion arithmetic. For example, it will convert 14:00 UTC to 14:00 UTC+1. This is most useful in cases where you have a timestamp with no timezone information, or a parser that isn't smart enough to understand the timezone information given.</p>
<p>(You need to know which of these two problems you have. It is not possible to automatically determine whether your datetime object has the "right" timezone information, because Python cannot guess your intentions.)</p>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 Change timestamp from dateutil from utc to not utc

 Ask Question
 Asked 4 years, 3 months ago
 Modified 4 years, 3 months ago
 Viewed 1k times
 0

 What exists

 import datetime
 import dateutil.parser
 import time
 
 timestamp = dateutil.parser.parse(response["body"]["inserted_at"])
 

 Whats the problem
 This timestamp is UTC, but it should be UTC+1, or TimeZone Europe,Zurich

 Question
 What shall I add to the existing code to have timestampas Europe,Zurich, and no moreUTC`?

 Thanks in advance

 * python
 * python-dateutil
 Share
 Improve this question
 Follow
 edited Nov 23, 2018 at 16:52
 Jab
 26.2k 21 21 gold badges 75 75 silver badges 114 114 bronze badges
 asked Nov 23, 2018 at 16:49
 Gamsner Gamsner
 117 1 1 silver badge 9 9 bronze badges
 2
 * What is the value of response["body"]["inserted_at"] ? Presumably some string containing a timestamp... does it have a time zone in it?
 – Kevin
 Nov 23, 2018 at 17:03
 * It is UTC in that timestamp
 – Gamsner
 Nov 23, 2018 at 18:18
 Add a comment |

 2 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 1

 You want to use the astimezone method of datetime.datetime. If you have a datetime in any time zone (e g. UTC) and want it in another zone, you use dt_new_tz = dt_old_tz.astimezone(new_tz)

 In this case, you want:

 from dateutil import tz
 zurich_tz = tz.gettz("Europe/Zurich")
 new_ts = timestamp.astimezone(zurich_tz)
 
 Share
 Improve this answer
 Follow
 edited Nov 23, 2018 at 18:10
 answered Nov 23, 2018 at 17:17
 Paul Paul
 10.1k 12 12 gold badges 48 48 silver badges 81 81 bronze badges
 1
 * Thank you Paul for this. It was the copy paste solution which worked perfect.
 – Gamsner
 Nov 24, 2018 at 7:52
 Add a comment |
 1

 The astimezone() method shown by Paul will adjust the date and time to match the new timezone. This is usually what you want. For example, if the timestamp you have is UTC, and you want to convert it to UTC+1 (or any other timezone), then you need to add an hour (or do some other arithmetic), which astimezone() does for you. It also takes care of daylight saving time or summer time, as well as numerous more substantial timezone irregularities.

 However, sometimes this is not what you want. For example, if you have a UTC+1 timezone which is incorrectly labeled as UTC, then astimezone() will add an hour, producing a UTC+2 datetime which is incorrectly labeled UTC+1. If that describes your problem, then you should use the replace() method instead of astimezone(). This will simply "relabel" the timezone without doing any conversion arithmetic. For example, it will convert 14:00 UTC to 14:00 UTC+1. This is most useful in cases where you have a timestamp with no timezone information, or a parser that isn't smart enough to understand the timezone information given.

 (You need to know which of these two problems you have. It is not possible to automatically determine whether your datetime object has the "right" timezone information, because Python cannot guess your intentions.)

 Share
 Improve this answer
 Follow
 answered Nov 23, 2018 at 18:43
 Kevin Kevin
 28.4k 9 9 gold badges 59 59 silver badges 80 80 bronze badges
 3
 * Likely if the timestamp contained an accurate time zone, the parser did the right thing.
 – Paul
 Nov 23, 2018 at 19:26
 * @Paul: As I said, astimezone() is usually the right thing to use.
 – Kevin
 Nov 23, 2018 at 19:32
 * Thank you Kevin for the knowledge to understand better.
 – Gamsner
 Nov 24, 2018 at 7:51
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * python-dateutil
 or ask your own question.

 * The Overflow Blog
 * ML and AI consulting-as-a-service (Ep. 541)
 * Why governments need open source more than ever
 * Featured on Meta
 * Ticket smash for [status-review] tag: Part Deux
 * We've added a "Necessary cookies only" option to the cookie consent popup
 * The [amazon] tag is being burninated
 * Microsoft Azure Collective launch and proposed tag changes
 * Temporary policy: ChatGPT is banned
 Visit chat

 Related

 3100
 How do I change the size of figures drawn with Matplotlib?
 3197
 How do I clone a list so that it doesn't change unexpectedly after assignment?
 2330
 Importing files from different folder
 300
 Convert UTC datetime string to local datetime
 104
 get UTC timestamp in python with datetime
 757
 How to make a timezone aware datetime object
 2746
 How can I remove a key from a Python dictionary?
 669
 Does Python's time.time() return the local or UTC timestamp?
 157
 Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone
 3282
 How do I select rows from a DataFrame based on column values?

 Hot Network Questions

 * Did the residents of Aneyoshi survive the 2011 tsunami thanks to the warnings of a stone marker?
 * Can a private person deceive a defendant to obtain evidence?
 * Keep escaped forward slashes in JSON string values with jq
 * How did Leo Tolstoy approve Maude's English translation of War and Peace? Did he speak good English already?
 * How safe it would be to look at the other planet in double-planet system with naked eye?
 * Why does interpolation with zeros introduce frequency artifacts?
 * How do I understand the Hodge operator in Yang-Mills Lagrangian?
 * Effective capacitance of a capacitor under DC-bias voltage
 * Seforim on Suffering
 * Can I use an 11-speed cassette with my 9 speed Claris bike?
 * How to describe professional experience in Python development if my code isn't shareable? [Can't share as per company policy]
 * Sci fi book about a character with an implant/enhanced capabilities who was hired to assassinate a member of elite society
 * In quantum field theory, why is vacuum considered to have the same properties as a particle?
 * Draw a circle with all possible squares within it
 * Identify T-shaped constellation
 * Is there a colloquial word/expression for a push that helps you to start to do something?
 * How can I remove these gaps in my table?
 * Post-apocalyptic published in Asimov's in the 1980s; main character named Georges - travels in time on highways (on foot)
 * How did this ceiling exhaust fan get stuck on (and why did disconnecting this wire fix it)?
 * Where to put an inheritance of $1.4 million upon first receiving it
 * How important is it to clearly understand requirements and architecture before starting to code?
 * How to print leading zeros (padding) in awk?
 * Which philosophers have considered irrational conviction
 * Why do game developers not make games with cheat codes or god mode any more?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.24.43259

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Necessary cookies only
 Customize settings
The astimezone() method shown by Paul will adjust the date and time to match the new timezone. This is usually what you want. For example, if the timestamp you have is UTC, and you want to convert it to UTC+1 (or any other timezone), then you need to add an hour (or do some other arithmetic), which astimezone() does for you. It also takes care of daylight saving time or summer time, as well as numerous more substantial timezone irregularities.
However, sometimes this is not what you want. For example, if you have a UTC+1 timezone which is incorrectly labeled as UTC, then astimezone() will add an hour, producing a UTC+2 datetime which is incorrectly labeled UTC+1. If that describes your problem, then you should use the  replace()  method instead of astimezone(). This will simply "relabel" the timezone without doing any conversion arithmetic. For example, it will convert 14:00 UTC to 14:00 UTC+1. This is most useful in cases where you have a timestamp with no timezone information, or a parser that isn't smart enough to understand the timezone information given.
(You need to know which of these two problems you have. It is not possible to automatically determine whether your datetime object has the "right" timezone information, because Python cannot guess your intentions.)
Change timestamp from dateutil from utc to not utc
https://stackoverflow.com/questions/53450395/change-timestamp-from-dateutil-from-utc-to-not-utc
https://stackoverflow.com/questions/3305413/how-to-preserve-timezone-when-parsing-date-time-strings-with-strptime
How to preserve timezone when parsing date/time strings with strptime()?
2022-04-18
Victorhooi Victorhooi
<div><div>
<p>The <a href="http://docs.python.org/library/datetime.html#datetime.datetime.strptime"><code>datetime</code> module documentation</a> says:</p>
<blockquote>
 <p>Return a datetime corresponding to date_string, parsed according to format. This is equivalent to <code>datetime(*(time.strptime(date_string, format)[0:6]))</code>.</p>
</blockquote>
<p>See that <code>[0:6]</code>? That gets you <code>(year, month, day, hour, minute, second)</code>. Nothing else. No mention of timezones.</p>
<p>Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to <code>time.strptime</code> doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.</p>
<p>It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:</p>
<blockquote>
 <p>When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.</p>
</blockquote>
<p>Note that this doesn't work with %Z, so the case is important. See the following example:</p>
<pre><code>In [1]: from datetime import datetime
In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')
In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None
In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')
In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00
</code></pre>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 How to preserve timezone when parsing date/time strings with strptime()?

 Ask Question
 Asked 12 years, 7 months ago
 Modified 10 months ago
 Viewed 299k times
 249

 I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where EST is an Australian time-zone):

 Tue Jun 22 07:46:22 EST 2010
 

 I need to be able to parse this date in Python. At first, I tried to use the strptime() function from datettime.

 >>> datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST', '%a %b %d %H:%M:%S %Y %Z')
 

 However, for some reason, the datetime object that comes back doesn't seem to have any tzinfo associated with it.

 I did read on this page that apparently datetime.strptime silently discards tzinfo, however, I checked the documentation, and I can't find anything to that effect documented here.

 Is there any way to get strptime() to play nicely with timezones?

 * python
 * datetime
 * timezone
 Share
 Follow
 edited Apr 18, 2022 at 20:26
 mkrieger1
 17.1k 4 4 gold badges 51 51 silver badges 58 58 bronze badges
 asked Jul 22, 2010 at 2:42
 victorhooi victorhooi
 16.2k 22 22 gold badges 89 89 silver badges 113 113 bronze badges
 4
 * 1
 Can't you just... convert all dates to GMT?
 – Robus
 Jul 22, 2010 at 2:48
 * 2
 @Robus: Hmm, I was hoping to do that - but I was assuming that strftime/datetime could somehow do that? Either way, I need to store/parse the fact that the datetimes are in the EST timezone, or whatever timezone they happen to me. The script needs to be able to parse generic datetimes with timezone info (e.g. ETC could be any other timezone).
 – victorhooi
 Jul 22, 2010 at 3:00
 * 4
 EST is also a US timezone abbreviation. (Similarly BST is both a UK and a Brazilian timezone abbrev.) Such abbreviations are just inherently ambiguous. Use offsets relative to UTC/GMT instead. (If you need to support abbreviations, you need to make the mapping locale-dependent and that's a messy rat-hole.)
 – Donal Fellows
 Jul 22, 2010 at 8:14
 * EST timezone abbreviation is ambiguous . See also: Parsing date/time string with timezone abbreviated name in Python?
 – jfs
 Aug 21, 2014 at 10:42
 Add a comment |

 5 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 437
 +100

 I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.

 >>> from dateutil import parser
 >>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
 datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
 >>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400")
 datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400))
 >>> parser.parse("Sun")
 datetime.datetime(2011, 12, 18, 0, 0)
 >>> parser.parse("10-11-08")
 datetime.datetime(2008, 10, 11, 0, 0)
 

 and so on. No dealing with strptime() format nonsense... just throw a date at it and it Does The Right Thing.

 Share
 Follow
 edited Apr 18, 2022 at 20:29
 mkrieger1
 17.1k 4 4 gold badges 51 51 silver badges 58 58 bronze badges
 answered Dec 15, 2011 at 18:52
 Joe Shaw Joe Shaw
 21.8k 16 16 gold badges 69 69 silver badges 92 92 bronze badges
 9
 * Given that so many people tend to use python-dateutil, I'd like to point us one limitation of that lib. >>> parser.parse("Thu, 25 Sep 2003 10:49:41,123 -0300") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/wanghq/awscli/lib/python2.7/site-packages/dateutil/parser.py", line 748, in parse return DEFAULTPARSER.parse(timestr, **kwargs) File "/Users/wanghq/awscli/lib/python2.7/site-packages/dateutil/parser.py", line 310, in parse res, skipped_tokens = self._parse(timestr, **kwargs) TypeError: 'NoneType' object is not iterable
 – wanghq
 Apr 29, 2014 at 0:16
 * 1
 @wanghq you need to replace the last comma with period. Then parser.parse("Thu, 25 Sep 2003 10:49:41.123 -0300") returns: datetime.datetime(2003, 9, 25, 10, 49, 41, 123000, tzinfo=tzoffset(None, -10800))
 – flyingfoxlee
 Aug 1, 2014 at 8:37
 * 8
 @flyingfoxlee, yes, I understand that. I just want to tell people the limitation of python-dateutil. It does magic things, but sometimes fails to do that. So "just throw a date at it and it Does The Right Thing." is not 100% true.
 – wanghq
 Aug 1, 2014 at 23:38
 * 6
 dateutil.parser.parse("10-27-2016 09:06 AM PDT") returns: datetime.datetime(2016, 10, 27, 9, 6) fails to figure out time zone...
 – HaPsantran
 Nov 1, 2016 at 1:12
 * 4
 It depends on one's goal. dateutil parser may be simple to use, but strptime() is faster. Besides, its formats are quite easy to learn.
 – rapture
 Nov 21, 2018 at 9:25
 | Show 4 more comments
 92

 The datetime module documentation says:

 Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

 See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.

 Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.

 It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:

 When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.

 Note that this doesn't work with %Z, so the case is important. See the following example:

 In [1]: from datetime import datetime
 
 In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')
 
 In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
 TZ NAME: None
 
 In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')
 
 In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
 TZ NAME: UTC+10:00
 
 Share
 Follow
 edited Apr 18, 2018 at 8:35
 mikey
 123 2 2 silver badges 9 9 bronze badges
 answered Jul 22, 2010 at 8:08
 John Machin John Machin
 80.5k 11 11 gold badges 139 139 silver badges 185 185 bronze badges
 1
 * 19
 Related Python bug: %Z in strptime doesn't match EST and others
 – jfs
 Sep 29, 2014 at 12:11
 Add a comment |
 85

 Since strptime returns a datetime object which has tzinfo attribute, We can simply replace it with desired timezone.

 >>> import datetime
 
 >>> date_time_str = '2018-06-29 08:15:27.243860'
 >>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
 >>> date_time_obj.tzname()
 'UTC'
 
 Share
 Follow
 answered Sep 21, 2020 at 8:04
 Surya Teja Surya Teja
 1,090 7 7 silver badges 9 9 bronze badges
 3
 * 4
 Not all timestamp strings are UTC-based (for example, the one in the question).
 – Mew
 Mar 21, 2021 at 22:56
 * 2
 This will not work correctly for many of timezone. For eg: doing this for Asia/Kolkata gives an offset of tzinfo=<DstTzInfo 'Asia/Kolkata' LMT+5:53:00 STD
 – Irfanuddin
 Jul 28, 2021 at 12:24
 * 5
 @iudeen what you describe is the result of an incorrectly localized pytz timezone object. With pytz, you must localize, don't use replace! With Python 3.9 however, you should use zoneinfo instead, which avoids that pitfall altogether. Safe to replace there.
 – FObersteiner
 Oct 22, 2021 at 8:53
 Add a comment |
 12

 Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

 >>> from email.utils import parsedate_tz
 >>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
 (2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)
 

 See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

 In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

 Share
 Follow
 edited Oct 7, 2021 at 5:49
 Community Bot
 1 1 1 silver badge
 answered Dec 4, 2015 at 10:27
 jfs jfs
 391k 189 189 gold badges 968 968 silver badges 1652 1652 bronze badges
 Add a comment |
 0

 Ran into this exact problem.

 What I ended up doing:

 # starting with date string
 sdt = "20190901"
 std_format = '%Y%m%d'
 
 # create naive datetime object
 from datetime import datetime
 dt = datetime.strptime(sdt, sdt_format)
 
 # extract the relevant date time items
 dt_formatters = ['%Y','%m','%d']
 dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
 
 # set timezone
 import pendulum
 tz = pendulum.timezone('utc')
 
 dt_tz = datetime(*dt_vals,tzinfo=tz)
 
 Share
 Follow
 edited Sep 5, 2019 at 15:52
 answered Sep 5, 2019 at 15:44
 Chris Chris
 27.5k 26 26 gold badges 77 77 silver badges 147 147 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * datetime
 * timezone
 or ask your own question.

 * The Overflow Blog
 * How edge functions move your back end close to your front end
 * ML and AI consulting-as-a-service (Ep. 541)
 * Featured on Meta
 * Ticket smash for [status-review] tag: Part Deux
 * We've added a "Necessary cookies only" option to the cookie consent popup
 * The [amazon] tag is being burninated
 * Microsoft Azure Collective launch and proposed tag changes
 * Temporary policy: ChatGPT is banned

 Linked

 3
 Date Format incorrect using strptime
 3
 Converting naive datetime object to UTC timezone
 1
 How to format +xxxx for strptime()
 0
 Time data format mismatch error
 0
 Why does Python's datetime strptime() not set timezone when %Z is specified in a string?
 0
 datetime.strptime ValueError in python
 300
 Convert UTC datetime string to local datetime
 35
 Convert an RFC 3339 time to a standard Python timestamp
 41
 Parsing date with timezone from an email?
 38
 Parsing date/time string with timezone abbreviated name in Python?
 See more linked questions

 Related

 563
 How can I get the current date and time in UTC or GMT in Java?
 498
 Create a Date with a set timezone without using a string representation
 1032
 How do I get the current date and time in PHP?
 361
 How to get the current date and time
 120
 Parsing an ISO8601 date/time (including TimeZone) in Excel
 595
 How to remove time portion of date in C# in DateTime object only?
 593
 How to initialize a JavaScript Date to a particular time zone
 0
 Generating current time in a chosen time zone
 21
 Python timezone '%z' directive for datetime.strptime() not available

 Hot Network Questions

 * Would merfolk need beds?
 * What led to the fall of shell accounts?
 * Draw a circle with all possible squares within it
 * Why would/wouldn't *humanoid* robots become popular, rather than any other robotic body-form?
 * How do gas turbine engines and turbofan engines keep constant compressor side rpm?
 * Why countries sometimes don't want to share intelligence on an investigation even if they are allies?
 * Question on Famine, Affluence and Morality
 * Why does the FET input stage of op-amps still have an input current limit?
 * What does it mean to "have had abolition of war"?
 * What is an important mathematical question?
 * How can you achieve decent clock accuracy in microcontrollers (e.g., max 1 second drift in a year)? How do digital watch manufacturers accomplish it?
 * What's the shear strength of a 5.0 x 50mm wood screw?
 * In a list, how to pick whatever is not f and it's derivatives?
 * At what technological level can a mixed-gender military not be at a disadvantage to an all-male one?
 * Breaking spokes
 * What space do I occupy after Polymorphing into a bigger creature?
 * How did Leo Tolstoy approve Maude's English translation of War and Peace? Did he speak good English already?
 * What is the meaning of kindled and sensitized in the following paragraph?
 * Golf 7 key stolen, which fuse to remove to disable car key reprogramming?
 * Looking for a SF/alternate history book about a 19th century style explorer who navigates lands with corrupted fauna and flora
 * Why do they not make games with cheat codes or god mode any more?
 * About an integral of the MIT Integration Bee Finals (2023)
 * Why is the Delta IV Heavy taller than the Delta IV Medium?
 * Ruy Lopez Main Line - Why not Be7 before Nf6?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.24.43259

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Necessary cookies only
 Customize settings
The  datetime module documentation says:
 Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).
See that [0:6]? That gets you (year, month, day, hour, minute, second). Nothing else. No mention of timezones.
Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.
It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:
 When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.
Note that this doesn't work with %Z, so the case is important. See the following example:
 In [1]: from datetime import datetime
In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')
In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None
In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')
In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00
How to preserve timezone when parsing date/time strings with strptime()?
https://stackoverflow.com/questions/3305413/how-to-preserve-timezone-when-parsing-date-time-strings-with-strptime
https://stackoverflow.com/questions/44159875/time-difference-with-different-time-formats-in-python3
Time difference with different time formats in Python3
2017-05-24
Davtho
<div><div>
 
<div>
 
 <div>
 
<p>Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser</p>
<p>I'm not sure what I need to do to parse them into the same format, but my two dates are:</p>
<pre><code>2017-05-24 15:40:00+00:00
2017-05-24 14:23:44.995015
</code></pre>
<p>If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?</p>
 </div>
 
 <div>
 <p>
 asked May 24, 2017 at 13:31
 </p>
 <div>
 <a href="/users/5053559/davtho1983"><p></p></a>
 </div>
 
</div>
 
</div>
 <div>
 
 
<div>
 
 <div>
<p>Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?</p>
<pre><code>import dateutil.parser
date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
date_delta = date1 - date2 # 1:16:15.004985
</code></pre>
<p>You can call <code>replace(microsecond=0)</code> on your dates to remove the microseconds.</p>
 </div>
 <div>
 <p>
 answered May 24, 2017 at 13:50
 </p>
 <div>
 <a href="/users/7553525/zwer"><p></p></a>
 </div>
 <div>
 <p><a href="/users/7553525/zwer">zwer</a>zwer</p><p>24.3k3 gold badges46 silver badges61 bronze badges
 </p>
 </div>
</div>
 
</div>
 
<div>
 
 <div>
<p>You could transform the second datetime (that is a timestamp) into the first one with this code:</p>
<pre><code>def convert_to_timestamp(string_date):
 the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
 return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
</code></pre>
<p>or:</p>
<pre><code>def transformTimestamps(timestamp_):
year = timestamp_[:4]
month = timestamp_[4:6]
day = timestamp_[6:8]
hour = timestamp_[9:11]
minute = timestamp_[11:13]
second = timestamp_[13:15]
microsecond = timestamp_[16:22]
myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
</code></pre>
<p>Then, you can calculate the difference between them.</p>
<p>I hope this help. Greetings!</p>
 </div>
 <div>
 <p>
 answered May 24, 2017 at 13:39
 </p>
 <div>
 <a href="/users/6287439/valeria-lobos-ossand%c3%b3n"><p></p></a>
 </div>
 
</div>
 
</div>
 
<div>
 
 <div>
<p>Probably you want to use this method</p>
<blockquote>
 <p>datetime.strptime(date_string, format)</p>
</blockquote>
<p>Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in</p>
<blockquote>
 <p>class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
 microsecond=0, tzinfo=None, *, fold=0)</p>
</blockquote>
<p>For more on this topic you can always read the python docs, you can find the same information I just gave you and more here:
<a href="https://docs.python.org/3/library/datetime.html">https://docs.python.org/3/library/datetime.html</a></p>
<p>Hope it helped.</p>
 </div>
 <div>
 <p>
 answered May 24, 2017 at 13:40
 </p>
 <div>
 <a href="/users/3819047/franco-roura"><p></p></a>
 </div>
 
</div>
 
</div>
 
 <h2>
 
 </h2>
 </div>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 Time difference with different time formats in Python3

 Ask Question
 Asked 5 years, 8 months ago
 Modified 5 years, 8 months ago
 Viewed 275 times
 0

 Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser

 I'm not sure what I need to do to parse them into the same format, but my two dates are:

 2017-05-24 15:40:00+00:00
 2017-05-24 14:23:44.995015
 

 If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?

 * python
 * datetime
 * python-3.5
 * python-dateutil
 Share
 Follow
 asked May 24, 2017 at 13:31
 Davtho1983 Davtho1983
 3,779 8 8 gold badges 50 50 silver badges 100 100 bronze badges
 Add a comment |

 3 Answers

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 2

 Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?

 import dateutil.parser
 
 date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
 date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
 
 date_delta = date1 - date2 # 1:16:15.004985
 

 You can call replace(microsecond=0) on your dates to remove the microseconds.

 Share
 Follow
 answered May 24, 2017 at 13:50
 zwer zwer
 24.3k 3 3 gold badges 46 46 silver badges 61 61 bronze badges
 Add a comment |
 0

 You could transform the second datetime (that is a timestamp) into the first one with this code:

 def convert_to_timestamp(string_date):
 the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
 return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
 

 or:

 def transformTimestamps(timestamp_):
 year = timestamp_[:4]
 month = timestamp_[4:6]
 day = timestamp_[6:8]
 hour = timestamp_[9:11]
 minute = timestamp_[11:13]
 second = timestamp_[13:15]
 microsecond = timestamp_[16:22]
 myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
 return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
 

 Then, you can calculate the difference between them.

 I hope this help. Greetings!

 Share
 Follow
 answered May 24, 2017 at 13:39
 Valeria Lobos Ossandón Valeria Lobos Ossandón
 311 1 1 gold badge 3 3 silver badges 10 10 bronze badges
 Add a comment |
 0

 Probably you want to use this method

 datetime.strptime(date_string, format)

 Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in

 class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

 For more on this topic you can always read the python docs, you can find the same information I just gave you and more here: https://docs.python.org/3/library/datetime.html

 Hope it helped.

 Share
 Follow
 answered May 24, 2017 at 13:40
 Franco Roura Franco Roura
 807 8 8 silver badges 26 26 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python
 * datetime
 * python-3.5
 * python-dateutil
 or ask your own question.

 * The Overflow Blog
 * Announcing more ways to learn and grow your skills
 * Why developer experience is the key to better software, straight from the...
 * Featured on Meta
 * Accessibility Update: Colors
 * 2022: a year in moderation
 * Collectives: The next iteration
 * We’re bringing advertisements for technology courses to Stack Overflow
 * Temporary policy: ChatGPT is banned
 Visit chat

 Related

 1644
 Calculate relative time in C#
 4491
 Difference between @staticmethod and @classmethod
 3113
 What is the difference between Python's list methods append and extend?
 3681
 How do I get the current time?
 2665
 Compare two dates with JavaScript
 3563
 What is the difference between __str__ and __repr__?
 2323
 Importing files from different folder
 223
 Difference between two dates in Python

 Hot Network Questions

 * Addition and multiplication are commutative but exponentiation and tetration are not. Do we know why?
 * Why are atoms electrically neutral?
 * Why are none of these chips identifiable?
 * The word "decant" for clone generation
 * What does it mean for two properties of objects to be of the same class (or even identical)?
 * Why does the Heisenberg uncertainty principle apply to particles?
 * Is an exhaust pipe broken at engine connection fixable by a DIYer?
 * Meaning of "nude" in Saxo Grammaticus
 * What is the difference between 冷える and 冷えている?
 * Ada and its candidate languages
 * Sum of Consecutive Squares
 * Inconsistent interline spacing in enumitem
 * Eyes stay stationary while posing rest of the mesh
 * When did Walter Benjamin say "We collect books in the belief that we are preserving them when in fact it is the books that preserve their collector"?
 * Non-inverting op-amp
 * Is it possible to define a topology on the real line such that 0 and non-zero integers are dense but no finite subset of non-zero integers is dense?
 * How do I erase sets of solutions from Solve based on criteria?
 * Why do Pokemon sometimes have dark stripes in Pokemon Go?
 * Why does Ontario have a quota on milk production?
 * Is there a circuit that takes two single-qubit states and reflects the second around the first?
 * EAS Build iOS Failure: Authentication with Apple Developer Portal failed
 * Computers lose power, lights dim. I suspect the mains power supply; is there anything I can do?
 * A very difficult functional equation
 * Why are there 23 members of the grand jury?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.3.43216

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Customize settings
Hi I have two times in slightly different formats and I need to work out the difference. The first was parsed from a ISO 8601 date using dateutil.parser
I'm not sure what I need to do to parse them into the same format, but my two dates are:
 2017-05-24 15:40:00+00:00
2017-05-24 14:23:44.995015
 
If they were both in datetime format I could just subtract one from the other, so I need to chop the milliseconds off both (coz that's not relevant to me), and tell python the new strings are both datetimes?
 
 
 
 
 asked May 24, 2017 at 13:31
 
 
    
 
 
 
 
 
 
 
 
Since you're already using dateutil, what's wrong with just removing the timezone (or adding it to the other) and subtracting them?
 import dateutil.parser
date1 = dateutil.parser.parse("2017-05-24 15:40:00+00:00").replace(tzinfo=None)
date2 = dateutil.parser.parse("2017-05-24 14:23:44.995015")
date_delta = date1 - date2 # 1:16:15.004985
 
You can call replace(microsecond=0) on your dates to remove the microseconds.
 
 
 
 answered May 24, 2017 at 13:50
 
 
    
 
 
  zwerzwer 24.3k3 gold badges46 silver badges61 bronze badges
 
 
 
 
 
 
You could transform the second datetime (that is a timestamp) into the first one with this code:
 def convert_to_timestamp(string_date):
 the_datetime = datetime.strptime(string_date.decode("utf-8"), "%Y%m%d.%H%M%S.%f")
 return time.mktime(the_datetime.timetuple()) * 1e6 + the_datetime.microsecond
 
or:
 def transformTimestamps(timestamp_):
year = timestamp_[:4]
month = timestamp_[4:6]
day = timestamp_[6:8]
hour = timestamp_[9:11]
minute = timestamp_[11:13]
second = timestamp_[13:15]
microsecond = timestamp_[16:22]
myformat = year+"-"+month+"-"+day+" +hour+":"+minute+":"+second+":"+microsecond
return datetime.strptime(myformat, '%Y-%m-%d %H:%M:%S:%f')
 
Then, you can calculate the difference between them.
I hope this help. Greetings!
 
 
 
 answered May 24, 2017 at 13:39
 
 
    
 
 
 
 
 
 
Probably you want to use this method
 datetime.strptime(date_string, format)
Also remember you can get rid of elements you do not want in your date (Like milliseconds) when you declare the specified date, as in
 class datetime.datetime(year, month, day, hour=0, minute=0, second=0,
 microsecond=0, tzinfo=None, *, fold=0)
For more on this topic you can always read the python docs, you can find the same information I just gave you and more here:
https://docs.python.org/3/library/datetime.html 
Hope it helped.
 
 
 
 answered May 24, 2017 at 13:40
Time difference with different time formats in Python3
https://stackoverflow.com/questions/44159875/time-difference-with-different-time-formats-in-python3
https://stackoverflow.com/questions/50679349/convert-string-having-timezone-into-to-utc-datetime-object-python
convert string having timezone into to utc datetime object python
2018-06-04
Anurag Sharma Anurag Sharma 4
<div><div>
 
<div>
 
 <div>
 
<p>I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version</p>
<p>My string is like - </p>
<pre><code>2018-05-04T05:22:52.3272611-04:00
</code></pre>
<p>I am not able to get much info on converting the given datetime to utc.</p>
 </div>
 
 <div>
 <p>
 asked Jun 4, 2018 at 11:17
 </p>
 <div>
 <a href="/users/1364646/anurag-sharma"><p></p></a>
 </div>
 <div>
 <p><a href="/users/1364646/anurag-sharma">Anurag Sharma</a>Anurag Sharma</p><p>4,72913 gold badges59 silver badges100 bronze badges
 </p>
 </div>
</div>
 
</div>
 <div>
 
 
<div>
 
 <div>
<p>That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use <a href="https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse"><code>dateutil.parser.isoparse</code></a> on it:</p>
<pre><code>from dateutil.parser import isoparse
from dateutil.tz import UTC
dt = isoparse('2018-05-04T05:22:52.327261-04:00')
dt.astimezone(UTC)
</code></pre>
<p>Otherwise you can use <a href="https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse"><code>dateutil.parser.parse</code></a>, which is slower but allows for more unusual formats:</p>
<pre><code>from dateutil.parser import parse
from dateutil.tz import UTC
dt = parse('2018-05-04T05:22:52.3272611-04:00')
dt.astimezone(UTC)
</code></pre>
<p>You should also use <code>parse</code> if you are not certain what the format will be.</p>
 </div>
 <div>
 <p>
 answered Jun 4, 2018 at 11:46
 </p>
 <div>
 <a href="/users/467366/paul"><p></p></a>
 </div>
 
</div>
 
</div>
 
 <h2>
 
 </h2>
 </div>
 </div>||||I|||| Stack Overflow
 1. About
 2. Products
 3. For Teams
 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 3. Talent Build your employer brand
 4. Advertising Reach developers & technologists worldwide
 5. About the company
 Loading…

 1. current community

 + Stack Overflow
 help chat
 + Meta Stack Overflow

 your communities

 Sign up or log in to customize your list.

 more stack exchange communities

 company blog
 2. 
 3. Log in
 4. Sign up
 1. Home
 2. 
 1. Public
 2. Questions
 3. Tags
 4. Users
 5. Companies
 6. Collectives
 7. Explore Collectives
 3. 
 1. Teams
 Stack Overflow for Teams – Start collaborating and sharing organizational knowledge. Create a free Team Why Teams?
 2. Teams
 3. Create free Team

 Collectives™ on Stack Overflow

 Find centralized, trusted content and collaborate around the technologies you use most.

 Learn more about Collectives

 Teams

 Q&A for work

 Connect and share knowledge within a single location that is structured and easy to search.

 Learn more about Teams

 convert string having timezone into to utc datetime object python

 Ask Question
 Asked 4 years, 8 months ago
 Modified 4 years, 8 months ago
 Viewed 6k times
 4

 I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version

 My string is like -

 2018-05-04T05:22:52.3272611-04:00
 

 I am not able to get much info on converting the given datetime to utc.

 * python-3.x
 * python-datetime
 * python-dateutil
 Share
 Improve this question
 Follow
 asked Jun 4, 2018 at 11:17
 Anurag Sharma Anurag Sharma
 4,729 13 13 gold badges 59 59 silver badges 100 100 bronze badges
 Add a comment |

 1 Answer

 Sorted by: Reset to default
 Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)
 13

 That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use dateutil.parser.isoparse on it:

 from dateutil.parser import isoparse
 from dateutil.tz import UTC
 
 dt = isoparse('2018-05-04T05:22:52.327261-04:00')
 dt.astimezone(UTC)
 

 Otherwise you can use dateutil.parser.parse, which is slower but allows for more unusual formats:

 from dateutil.parser import parse
 from dateutil.tz import UTC
 
 dt = parse('2018-05-04T05:22:52.3272611-04:00')
 dt.astimezone(UTC)
 

 You should also use parse if you are not certain what the format will be.

 Share
 Improve this answer
 Follow
 edited Jun 4, 2018 at 11:52
 answered Jun 4, 2018 at 11:46
 Paul Paul
 10k 12 12 gold badges 48 48 silver badges 81 81 bronze badges
 Add a comment |

 Your Answer

 Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your research!

 But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal experience.

 To learn more, see our tips on writing great answers.

 Sign up or log in

 Sign up using Google
 Sign up using Facebook
 Sign up using Email and Password
 Submit

 Post as a guest

 Name
 Email

 Required, but never shown

 Post as a guest

 Name
 Email

 Required, but never shown

 Post Your Answer Discard

 By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

 Not the answer you're looking for? Browse other questions tagged
 * python-3.x
 * python-datetime
 * python-dateutil
 or ask your own question.

 * The Overflow Blog
 * Announcing more ways to learn and grow your skills
 * Why developer experience is the key to better software, straight from the...
 * Featured on Meta
 * Accessibility Update: Colors
 * 2022: a year in moderation
 * Collectives: The next iteration
 * We’re bringing advertisements for technology courses to Stack Overflow
 * Temporary policy: ChatGPT is banned

 Related

 736
 What is the best way to remove accents (normalize) in a Python unicode string?
 3564
 Convert bytes to a string
 308
 How to convert a UTC datetime to a local datetime using only standard library?
 752
 How to make a timezone aware datetime object
 1389
 Best way to convert string to bytes in Python 3?
 2872
 Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
 595
 Error: " 'dict' object has no attribute 'iteritems' "
 851
 "TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3
 0
 How to convert a UTC date string to timezone aware datetime object in Python3?
 1
 Convert UTC datetime to UTC epoch

 Hot Network Questions

 * How to adapt a spoke salvaged from a 26" wheel to a 24" one?
 * Anydice: "highest 1 of 3d6 1d12" function. Is this correct?
 * Determining the optimize lambda in Multi-Objective Optimization
 * Intel 80188 & 8087 clock frequency differences
 * A standard way of marking alternate tunings for classical guitar?
 * Why does the Heisenberg uncertainty principle apply to particles?
 * Is an exhaust pipe broken at engine connection fixable by a DIYer?
 * Do distinctions and concepts exist?
 * Why Is It Important To Simulate Data From A Statistical Model?
 * Two questions about the 4th verse of "The Star-Spangled Banner"
 * Why did Harry and the others think they could rescue Sirius?
 * How can one order cheeses for a cheese tasting event?
 * Why do Pokemon sometimes have dark stripes in Pokemon Go?
 * Stable words in the Proto-Indo-European language family
 * How do we use lowercase `\mathcal` or `\mathscr` in latex overleaf?
 * Juvenile SF Novel With Conflict between Earth Humans and Colonists
 * In an underdetermined linear regression setup, why does the residual sum of squares equal 0?
 * Table of unequal sequence
 * Idiomatic guitar notation; notating L.V. passages?
 * How big of an explosion can you make with a fusion reactor?
 * How many spells require expensive components for each casting?
 * Can an aircraft use ram air to generate power while flying?
 * Why is the solstice the first day of summer, and not the central day?
 * Calculating XOR from 1 to n: Why does this method work?
 more hot questions
 Question feed

 Subscribe to RSS

 Question feed

 To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

 Stack Overflow

 * Questions
 * Help

 Products

 * Teams
 * Advertising
 * Collectives
 * Talent

 Company

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

 Stack Exchange Network

 * Technology
 * Culture & recreation
 * Life & arts
 * Science
 * Professional
 * Business
 * API
 * Data
 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

 Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2023.2.6.43219

 Your privacy

 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 Accept all cookies Customize settings
I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version
My string is like - 
 2018-05-04T05:22:52.3272611-04:00
 
I am not able to get much info on converting the given datetime to utc.
 
 
 
 
 asked Jun 4, 2018 at 11:17
 
 
    
 
 
  Anurag SharmaAnurag Sharma 4,72913 gold badges59 silver badges100 bronze badges
 
 
 
 
 
 
 
 
That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use  dateutil.parser.isoparse  on it:
 from dateutil.parser import isoparse
from dateutil.tz import UTC
dt = isoparse('2018-05-04T05:22:52.327261-04:00')
dt.astimezone(UTC)
 
Otherwise you can use  dateutil.parser.parse , which is slower but allows for more unusual formats:
 from dateutil.parser import parse
from dateutil.tz import UTC
dt = parse('2018-05-04T05:22:52.3272611-04:00')
dt.astimezone(UTC)
 
You should also use parse if you are not certain what the format will be.
 
 
 
 answered Jun 4, 2018 at 11:46
convert string having timezone into to utc datetime object python
https://stackoverflow.com/questions/50679349/convert-string-having-timezone-into-to-utc-datetime-object-python