51

How to make sure the datetime.date.today() is converted to UTC time?

This is my code so far:

#today : 2014-12-21
today = datetime.date.today()

#1900-01-01 16:00:00+00:00
timeformat = datetime.datetime.strptime('16:00', '%H:%M').replace(tzinfo=pytz.utc)

#combine today and timeformat  2014-12-21 16:00:00
now = datetime.datetime.combine(u, timeformat.time())
str_now =  now.strftime("%Y-%m-%d %H:%M:%S")

2 Answers 2

96

Use utcnow:

today = datetime.datetime.utcnow().date()
3
  • 1
    it is not correct unless midnight in local time (date.today()) is the same time instance as midnight in UTC (.utcnow().date()). See How do I get the UTC time of “midnight” for a given timezone?
    – jfs
    Commented Dec 8, 2015 at 20:08
  • What does it have to do with midnight? It just gets the date that UTC is in right now.
    – webjunkie
    Commented Feb 26, 2016 at 10:57
  • 6
    @webjunkie: look at the question title, notice: date.today() there. It returns the date in the local timezone. That value changes at midnight in the local timezone. At 23:59:59 it is one day, 00:00:00 it is another. Are you following? That moment: 00:00 in the local timezone corresponds to different UTC time depending on the local timezone e.g., 2016-02-27 00:00 in New York corresponds to 2016-02-27 05:00 UTC. If the question title were "what is the current date in UTC right now"; I would agree with you.
    – jfs
    Commented Feb 27, 2016 at 17:13
-5

for printing date with time you can use ...

tomorrow =  twtomorrow.strftime("%Y-%m-%d %H:%M:%S")

instead of

tomorrow =  twtomorrow.strftime("%Y-%m-%d")

Your Answer

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 or ask your own question.