Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

557
Views
Python Datetime : use strftime() with a timezone-aware date

Suppose I have date d like this :

>>> d 
datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

As you can see, it is "timezone aware", there is an offset of 2 Hour, utctime is

>>> d.utctimetuple() 
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19, 
                 tm_hour=23, tm_min=12, tm_sec=0, 
                 tm_wday=6, tm_yday=109, tm_isdst=0)

So, real UTC date is 19th March 2009 23:12:00, right ?

Now I need to format my date in string, I use

>>> d.strftime('%Y-%m-%d %H:%M:%S.%f') 
'2009-04-19 21:12:00.000000'

Which doesn't seems to take this offset into account. How to fix that ?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

In addition to what @Slam has already answered:

If you want to output the UTC time without any offset, you can do

from datetime import timezone, datetime, timedelta
d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2)))
d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')

See datetime.astimezone in the Python docs.

over 4 years ago · Santiago Trujillo Report

0

The reason is python actually formatting your datetime object, not some "UTC at this point of time"

To show timezone in formatting, use %z or %Z.

Look for strf docs for details

over 4 years ago · Santiago Trujillo Report

0

This will convert your local time to UTC and print it:

import datetime, pytz
from dateutil.tz.tz import tzoffset

loc = datetime.datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

print(loc.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S.%f') )

(http://pytz.sourceforge.net/)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!