34

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")
user2492364
  • 6,047
  • 18
  • 74
  • 137

2 Answers2

75

Use utcnow:

today = datetime.datetime.utcnow().date()
Daniel
  • 40,885
  • 4
  • 53
  • 79
  • 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?](http://stackoverflow.com/questions/373370/how-do-i-get-the-utc-time-of-midnight-for-a-given-timezone) – jfs Dec 08 '15 at 20:08
  • What does it have to do with midnight? It just gets the date that UTC is in right now. – webjunkie Feb 26 '16 at 10:57
  • 3
    @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 Feb 27 '16 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")
techdreams
  • 4,993
  • 7
  • 41
  • 58
shivam garg
  • 487
  • 4
  • 6