7

The output of datetime.datetime.now() outputs in my native timezone of UTC-8. I'd like to convert that to an appropriate timestamp with a tzinfo of UTC.

from datetime import datetime, tzinfo
x = datetime.now()
x = x.replace(tzinfo=UTC)

^ outputs NameError: name 'UTC' is not defined

x.replace(tzinfo=<UTC>) outputs SyntaxError: invalid syntax

x.replace(tzinfo='UTC') outputs TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'

What is the correct syntax to use to accomplish my example?

Randall Ma
  • 10,486
  • 9
  • 37
  • 45
  • 1
    Python's standard libraries don't include any tzinfo classes, including UTC. The documentation does include instructions for creating one though. – Mark Ransom Jul 05 '12 at 23:00

2 Answers2

11

You'll need to use an additional library such as pytz. Python's datetime module doesn't include any tzinfo classes, including UTC, and certainly not your local timezone.

Edit: as of Python 3.2 the datetime module includes a timezone object with a utc member. The canonical way of getting the current UTC time is now:

from datetime import datetime, timezone
x = datetime.now(timezone.utc)

You'll still need another library such as pytz for other timezones. Edit: Python 3.9 now includes the zoneinfo module so there's no need to install additional packages.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
3

If all you're looking for is the time now in UTC, datetime has a builtin for that:

x = datetime.utcnow()

Unfortunately it doesn't include any tzinfo, but it does give you the UTC time.

Alternatively if you do need the tzinfo you can do this:

from datetime import datetime
import pytz
x = datetime.now(tz=pytz.timezone('UTC'))

You may also be interested in a list of the timezones: Python - Pytz - List of Timezones?

Community
  • 1
  • 1
fantabolous
  • 21,470
  • 7
  • 54
  • 51