1

I have these dates

  • 2016-02-26 12:12:12
  • 2016-02-friday 12:12:12

(Those two dates refers to the same day)

If I convert the first one in a timestamp and then convert it back in a readable format it works.

But if I try the same on the second one it does not convert back to the right day !

Here's what I did :

sTimestamp = time.mktime(
       datetime.datetime.strptime(
             "2016-02-26 12:12:12",
             "%Y-%m-%d %H:%M:%S")
      .timetuple())
print("date from timestamp = " +
       datetime.datetime.fromtimestamp(int(sTimestamp))
       .strftime('%Y-%m-%d %H:%M:%S'))

sTimestamp = time.mktime(
       datetime.datetime.strptime(
              "2016-02-friday 12:12:12",
              "%Y-%m-%A %H:%M:%S")
      .timetuple())
print("date from timestamp = " + 
       datetime.datetime.fromtimestamp(int(sTimestamp)).
       strftime('%Y-%m-%d %H:%M:%S'))

The output of thoses two lines are :

  • date from timestamp = 2016-02-26 12:12:12
  • date from timestamp = 2016-02-01 12:12:12

As you can see the first one is back to 26 but the second one converts back to 01 for an unknown reason. And by the way, 01 is a monday...

For information I am using python 3.4 and I am on Windows.

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
Doctor
  • 7,115
  • 4
  • 37
  • 55

1 Answers1

1

The first problem:

(Those two dates refers to the same day)

No, they don't. The first one refers to the last Friday of February in the year 2016; the second refers to, at best, a Friday in February in the year 2016.

Further, strptime is meant to be used with numbers as strings like "Friday" are not exact. The Python docs say:

For time objects, the format codes for year, month, and day should not be used, as time objects have no such values. If they’re used anyway, 1900 is substituted for the year, and 1 for the month and day.

So it looks like using inexact values such as "Friday" use the same fallback of defaulting to 1.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Humm ok ! Thanks for your answer. Any idear how to still do what I want ? – Doctor Feb 24 '16 at 19:55
  • @Doctor: If what you want is to get `26` from `friday`, no. With some extra code the best you could expect as a list of all Fridays in February (or the first Friday, or the last friday, or the most recent Friday, or the next Friday) -- but you'll have to figure out which one you want. – Ethan Furman Feb 24 '16 at 20:00
  • @Doctor: if you know that you always want "the last friday"; you could [use `dateutil.relativedelta()`](http://stackoverflow.com/a/12687078/4279). – jfs Feb 25 '16 at 13:15
  • I'll try that. Thanks. – Doctor Feb 25 '16 at 13:51
  • @J.F.Sebastian: Thanks for that link. I knew such packages were out there, but I don't use them so couldn't remember any to suggest. – Ethan Furman Feb 25 '16 at 16:55