0

I am trying to convert the local time to "UTC" time.

Followed this guide: How do I convert local time to UTC in Python?

But issue here is with the type of date which we giving here.

import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)

In the above code input is "2001-2-3 10:11:12" (string), But in my case it will be a datetime object.

begin = begin.replace(hour=0, minute=0, second=0, microsecond=0)

Someone let me know how we can achieve the conversion here.

Community
  • 1
  • 1
Sparky
  • 91
  • 1
  • 8

2 Answers2

0

Your string format needs a bit of a modification. You just need the leading zeros in your month and day:

import pytz, datetime
local = pytz.timezone("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-02-03 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive)
utc_dt = local_dt.astimezone(pytz.utc)
Scratch'N'Purr
  • 9,959
  • 2
  • 35
  • 51
0

If your input (begin) is not a time string but it is a naive (no timezone info) datetime object already then drop datetime.strptime() line (that parses the time string into datetime object) from the example. To convert a given naive datetime object that represents local time to utc:

import pytz    # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
local_dt = local_timezone.localize(begin, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670